我有一个NSArray<NSString*>*
对象,我需要调用一个C API,它接受一个字符串数组char**
。
最好的方法是什么?重要的注意事项是c字符串不能包含const
修饰符,因此以下内容不够好UTF8String
返回const char*
:
NSArray<NSString*>* names = ...;
int len = args.count;
char* cNames[len];
for( int i = 0; i < len; i++ ) {
cNames[i] = names[i].UTF8String;
};
答案 0 :(得分:1)
你需要做一些动态内存,因为你不能依赖正在发布的UTF8String的后备内存。
NSArray *strings = @[ @"String 1", @"Other string", @"Random String"];
char **cStrings = NULL;
NSInteger numCStrings = strings.count;
if (numCStrings) {
cStrings = (char **)calloc(numCStrings, sizeof(char*)) ;
if (cStrings) {
// Safer to allocate memory for each string
for (NSInteger i=0;i<numCStrings;i++) {
NSString *nsString = strings[i];
char *cString = (char *)malloc([nsString lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1); // + 1 for \0
if (cString) {
strcpy(cString, nsString.UTF8String);
cStrings[i] = cString;
} else {
// You should handle your error
}
}
} else {
// You should handle your error
}
}
for (NSInteger i=0;i<numCStrings;i++) {
NSLog(@"C-String (%ld): %s", i, cStrings[i]);
}
// Note you need to free your memory later!
// Do any additional setup after loading the view, typically from a nib.
for (NSInteger i=0;i<numCStrings;i++) {
if (cStrings[i]) {
// Free each string
free(cStrings[i]);
}
}
// Free the array
free(cStrings);
cStrings = NULL;
numCStrings = 0;