简体   繁体   English

从ObjC传递char数组到C

[英]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 ]. 我有一个包含纯c代码和由ObjC编译器[ .m file ]处理的c代码的项目。 The one handled by ObjC compiler has a following class: 由ObjC编译器处理的类具有以下类别:

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. dMessage是一个充满文本的NSData对象。

On C side, I do: 在C端,我这样做:

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

After the call, msg is empty, but the length variable is set to correct size. 调用后, msg为空,但长度变量设置为正确的大小。

What should I do to pass char* between objc and c? 我应该怎么做才能在objc和c之间传递char*

Thank you 谢谢

You're passing the wrong arguments to calloc() . 您将错误的参数传递给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. 由于第二个参数是NSDatabytes指针,因此您实际上在请求一些大的分配。 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);

It was a mistake in my code. 这是我的代码中的错误。

I should havecalled 我应该打电话

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

instead of 代替

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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