1

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Ah, sorry I forgot I tried that last night. I don't get EXC_BAD_ACCESS when I do that, but the two strings are both being assigned to argv[0] and I'm trying to get them into argv[0] and argv[1]. Or do I just need to have the cFunction split them on whitespace?
You could break a string on whitespaces, but in order to pass the function an array of C strings, you will need to reserve spa ce for the array, and store the pointers to each C string into it.
I'm making my args by appending textField2 to textField1, with a @" " in between, and my cFunction has "textField1string textField2string" in it.
Ah so you're saying make my NSArray hold the *cStrings instead of the [textField stringValue]s and then pass the NSArray?
for example : char * array [4] = {"one", "two", "three", "four"};.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.