简体   繁体   English

从C调用Objective C

[英]Calling Objective C from C

I have a callback function in C which looks like this: 我在C中有一个回调函数,如下所示:

 void cfunc(char* labelUpdateText)

This callback function is supposed to update the text of a label in my app's UI by changing the label's current text to whatever labelUpdateText is. 此回调函数应该通过将标签的当前文本更改为labelUpdateText的任何内容来更新应用程序UI中标签的文本。

So in cfunc I'm trying to call this Objective C function: 所以在cfunc中我试图调用这个Objective C函数:

-(void)updateLabel:(char*) text
{
    [_labelProp setStringValue:[NSString stringWithFormat:@"%@", [NSString stringWithUTF8String:text]]];
}

However, I can't call the objective C function from my C function. 但是,我不能从我的C函数调用目标C函数。

I tried like this: 我试过这样的:

updateLabel:labelUpdateText

But when I build the code, I get the warning 'Expression result unused' 但是当我构建代码时,我收到警告'表达结果未使用'

And the 'updateLabel:labelUpdateText' doesn't execute. 并且'updateLabel:labelUpdateText'不会执行。

What am I doing wrong? 我究竟做错了什么?

PS: I am new to Objective C! PS:我是Objective C的新手!

You need to provide the callback function with a pointer to the view containing the label and some means of updating it. 您需要为回调函数提供指向包含标签的视图的指针以及一些更新它的方法。 All callback functions should have a context pointer of some sort which can hold information allowing them to perform context-specific actions. 所有回调函数都应该有一个某种上下文指针 ,它可以保存信息,允许它们执行特定于上下文的操作。 If you cannot change the callback function semantics then you are stuck I'm afraid, however if you can, do it something like this: 如果你不能改变回调函数的语义,那么你就会陷入困境,但是如果可以的话,你可以这样做:

void cfunc(const char *labelUpdateText, void *contextInfo) {
    YourView *view = (YourView *)contextInfo;
    [view updateLabelWithText:[NSString stringWithUTF8String:labelUpdateText]];
}

You will need to provide the updateLabelWithText method in YourView and if you are using ARC there will be some bridging to do as well during the casting of contextInfo (the compiler will help you there though). 您需要在YourView提供updateLabelWithText方法,如果您正在使用ARC,那么在转换contextInfo期间也会有一些桥接(编译器会帮助您)。

为什么不在Objective C类中创建一个包装器C函数来调用ObjC语法并从需要进行回调的C程序中调用C函数。

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

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