user1872384
user1872384

Reputation: 7127

NSString to const void *

How to convert NSString to const void?

I've tried

NSString *testString = @"testString";
const void *testConstVoid = CFBridgingRetain(testString);

But testConstVoid is still an nsstring

Upvotes: 1

Views: 479

Answers (2)

battlmonstr
battlmonstr

Reputation: 6280

In addition to UTF8String you have cStringUsingEncoding: and getCString:maxLength:encoding:.

In the first 2 cases you need to copy the returned C string to your own char buffer or NSData if you plan to use it past the original NSString lifetime:

NSString *str = @"hello";
const char *cStr = str.UTF8String;
const NSUInteger cStrLen = [str lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSMutableData *cStrData = [[NSMutableData alloc] initWithBytes:cStr
                                                        length:cStrLen + 1];
    // +1 for '\0' (C string null-terminator)
const void *cStrBytes = cStrData.bytes;

Upvotes: 0

trungduc
trungduc

Reputation: 12144

Instead of CFBridgingRetain(testString), you should use testString.UTF8String

NSString *testString = @"testString";
const void *testConstVoid = testString.UTF8String;

Result

enter image description here

Upvotes: 1

Related Questions