MusiGenesis
MusiGenesis

Reputation: 75396

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.

Upvotes: 2

Views: 2037

Answers (4)

diatrevolo
diatrevolo

Reputation: 2822

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...

Upvotes: 1

MusiGenesis
MusiGenesis

Reputation: 75396

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];

Upvotes: 1

filipe
filipe

Reputation: 3380

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.

Upvotes: 7

Nimrod
Nimrod

Reputation: 5133

Check out the following in the NSString docs:

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

Upvotes: 1

Related Questions