Krystian
Krystian

Reputation: 3423

Passing char array from ObjC to C

I've got a project with a pure c code and c code handled by the ObjC compiler [.m file]. The one handled by ObjC compiler has a following class:

unsigned long getMessage(char ** message) {
 *message = (char*)calloc(1, [dMessage bytes], [dMessage length]);
 memcpy(message, [dMessage bytes], [dMessage length])
return [dMessage length];
}

dMessage is an NSData object filled with text.

On C side, I do:

char* msg = NULL
unsigned long length = getMessage(&msg)

After the call, msg is empty, but the length variable is set to correct size.

What should I do to pass char* between objc and c?

Thank you

Upvotes: 0

Views: 72

Answers (2)

Krystian
Krystian

Reputation: 3423

It was a mistake in my code.

I should havecalled

memcpy(*message, [dMessage bytes], [dMessage length])

instead of

memcpy(message, [dMessage bytes], [dMessage length])

Upvotes: 0

Ken Thomases
Ken Thomases

Reputation: 90571

You're passing the wrong arguments to calloc(). It takes two arguments, but you're passing three. The compiler should be screaming at you about that.

Since the second argument is the bytes pointer from the NSData, you're effectively requesting some huge allocation. It's probably failing. There would usually be a message logged to the console about that failure.

You want:

*message = (char*)calloc([dMessage length], 1);

Upvotes: 1

Related Questions