开发者

Calling a C function from Objective-C with string array

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 [textField开发者_运维技巧1 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜