Skip to content

Instantly share code, notes, and snippets.

@HalCanary
Last active March 31, 2022 23:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HalCanary/da0daa49e42f6f40aa240cf914c397a5 to your computer and use it in GitHub Desktop.
Save HalCanary/da0daa49e42f6f40aa240cf914c397a5 to your computer and use it in GitHub Desktop.
strdup NSString to C string
#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