Last active
March 31, 2022 23:26
-
-
Save HalCanary/da0daa49e42f6f40aa240cf914c397a5 to your computer and use it in GitHub Desktop.
strdup NSString to C string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
#include <stdlib.h> | |
static inline char* strdupNS(NSString* nss) { | |
static const NSStringEncoding enc = NSUTF8StringEncoding; | |
NSUInteger len = [nss lengthOfBytesUsingEncoding:enc]; | |
if (len <= 0) { | |
return NULL; | |
} | |
char* cstr = malloc((size_t)(1 + len)); | |
if (![nss getCString:cstr maxLength:(1 + len) encoding:enc]) { | |
free(cstr); | |
return NULL; | |
} | |
return cstr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment