简体   繁体   中英

How can I pass a string to a C function from Objective-C and get a value back?

I have an Objective-C view controller class, from which I am trying to call a straight-C (not Objective-C) function. I want to pass in a string variable by reference, set its value inside the C function, and then back in my view controller I want to convert this to a normal NSString object.

Since I can't pass in an NSString object directly, I need to create and pass in either a char pointer or a char array, and then convert it to an NSString object after the function returns.

Can anyone point me to a simple code example that shows how to do this? I'm not strong in either Objective-C or regular C, so manipulating strings is extremely difficult for me.

Maybe something like this

bool doSomethingToMyString(const char* originalString, char *buffer, unsigned int size)
{
    bool result = 0;
    if (size >= size_needed)
    {
        sprintf(buffer, "The new content for the string, maybe dependent on the originalString.");
        result = 1;
    }
    return result;
}

...
- (void) objectiveCFunctionOrSomething:(NSString *)originalString
{
    char myString[SIZE];
    if (doSomethingToMyString([originalString UTF8String], myString, SIZE))
    {
        NSString *myNSString = [NSString stringWithCString:myString encoding:NSUTF8StringEncoding];
        // alright!
    }
}

or, you know, something to that effect.

Check out the following in the NSString docs:

– cStringUsingEncoding:
– getCString:maxLength:encoding:
– UTF8String
+ stringWithCString:encoding:

Well, I got it to work. Here is my C function:

int testPassingChar(char buffer[]) {    
    strcpy(buffer, "ABCDEFGHIJ");
    return 0;
}

And then from Objective-C:

char test[10];
int i;
i = testPassingChar(test);
NSString* str = [[NSString alloc] initWithBytes:test length:sizeof(test) 
    encoding:NSASCIIStringEncoding];

Why don't you wrap your C function in Objective-C?

-(NSString*)testPassingCharWithStringLength:(int)whateverLength {
     char *test = malloc(sizeof(char) * whateverLength);  
     //do whatever you need to *test here in C
     NSString *returnString = [NSString stringWithUTF8String:test];
     free(test);
     return returnString;
}

...for example...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM