如何将 NSString 数组转换为 C 字符串数组?

How to convert an array of NSString to an array of c-strings?

我有一个 NSArray<NSString*>* 对象,我需要调用一个 C API,它接受一个字符串数组作为 char**

最好的方法是什么?重要的是 c 字符串不能有 const 修饰符,所以像下面这样的东西不够好,因为 UTF8String returns const char*:

NSArray<NSString*>* names = ...;
int len = args.count;
char* cNames[len];
for( int i = 0; i < len; i++ ) {
    cNames[i] = names[i].UTF8String;
};

你会想要做一些动态内存,因为你不能依赖正在释放的 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 [=10=]

            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;