Reputation: 57
I'm trying to call a simple tutorial C function from Objective-C and I can't figure out how to split up the arguments being passed, which is two strings.
int cFunction(int argc, char **argv)
{
int i;
printf("argc = %d\n", argc);
for (i = 0; i < argc; i++) {
printf("argv[%d] = \"%s\"\n", i, argv[i]);
}
return 0;
}
I've tried cFunction(3, "string1 string2")
, cFunction(3, "string1", "string2")
, and cFunction(3, args)
, with args
being an NSArray composed of [textField1 stringValue]
and [textField2 stringValue]
I get EXC_BAD_ACCESS when trying to printf argv[i]
. I've also tried passing 2 as the value of argc.
How should this be called? Thanks
Upvotes: 1
Views: 377
Reputation:
In this function parameter list, argv
is a pointer to a C string array (char **
).
Using the Objective-C NSString
or NSArray
type isn't possible with this function, First, convert each string using -(const char *)cStringUsingEncoding:(NSStringEncoding)encoding;
, and store them into a C array of strings.
// myString is "arg1"
// mySecondString is "arg2"
char *cString = [myString
cStringUsingEncoding:NSUTF8StringEncoding];
char *cSecondString = [mySecondString
cStringUsingEncoding:NSUTF8StringEncoding];
char *myStrings[2] = { cString, cSecondString };
int returnCode = cFunction(2, myStrings);
This should work.
Upvotes: 3