John Cashew
John Cashew

Reputation: 1094

How to do objective c style assignments after renaming file to .mm

This code compiles in a .m file, but not in an .mm file:

CFDataRef nativeSocket = CFWriteStreamCopyProperty((CFWriteStreamRef)outputStream, kCFStreamPropertySocketNativeHandle);
CFSocketNativeHandle *sock = (CFSocketNativeHandle *)CFDataGetBytePtr(nativeSocket);

The error message is:

Cannot initialize a variable of type 'CFDataRef' (aka 'const __CFData *') with an rvalue of type 'CFTypeRef' (aka 'const void *')

If I change the type of nativeSocket to CFTypeRef the error message becomes:

Candidate function not viable: cannot convert argument of incomplete type 'CFTypeRef' (aka 'const void *') to 'CFDataRef' (aka 'const __CFData *')

Please tell me how to fix this. I can't seem to guess what to google.

Thanks!

Upvotes: 3

Views: 143

Answers (1)

Ken Thomases
Ken Thomases

Reputation: 90721

You just need to cast the result from CFWriteStreamCopyProperty() to the proper type:

CFDataRef nativeSocket = (CFDataRef)CFWriteStreamCopyProperty((CFWriteStreamRef)outputStream, kCFStreamPropertySocketNativeHandle);
CFSocketNativeHandle *sock = (CFSocketNativeHandle *)CFDataGetBytePtr(nativeSocket);

It's probably safer to extract the native handle this way, though:

CFSocketNativeHandle sock;
CFDataGetBytes(nativeSocket, CFRangeMake(0, sizeof(sock)), (UInt8*)&sock);

That avoids any issue with the data object's byte pointer being misaligned. Also, it ensures that you don't try to deference the byte pointer implicitly (by doing *sock) after the data object has been released.

Upvotes: 1

Related Questions