是否有任何简单的方法可以将 NSStrings 的 Objective-C 持有类转换为接受 char * 变量列表的函数的参数?具体来说,我有一个类似的功能:
-(void)someFunction:(NSSomething *) var
我想转发到一个 C 函数,例如
void someCFunction(char * var, ...)
有没有简单的方法可以解决这个问题?
最佳答案
不,只有在编译时已知您传递的参数数量时,您才能执行您想要的操作。如果您只想转换单个字符串,请使用 -UTF8String
message :
// Example with two strings
NSString *str1 = ...;
NSString *str2 = ...;
someCFunction([str1 UTF8String], [str2 UTF8String]); // etc.
但是,如果字符串数量在运行时发生变化,您将需要使用不同的 API(如果有)。例如,如果有一个 API 接受字符串数组,您可以将 Objective-C 数组转换为 C 数组:
// This function takes a variable number of strings. Note: in C/Objective-C
// (but not in C++/Objective-C++), it's not legal to convert 'char **' to
// 'char *const *', so you may sometimes need a cast to call this function
void someCFunction(const char *const *stringArray, int numStrings)
{
...
}
...
// Convert Objective-C array to C array
NSArray *objCArray = ...;
int numStrings = [objCArray count];
char **cStrArray = malloc(numStrings * sizeof(char*));
for (int i = 0; i < count; i++)
cStrArray[i] = [[objCArray objectAtIndex:i] UTF8String];
// Call the function; see comment above for note on cast
someCFunction((const char *const *)cStrArray, numStrings);
// Don't leak memory
free(cStrArray);
关于objective-c - NSString(或 NSArray 或其他)到 C (char *) 字符串的可变参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10491800/