【问题标题】:How to call objective-C function from a C function如何从 C 函数调用目标 C 函数
【发布时间】:2010-08-07 00:11:02
【问题描述】:

我正在尝试从 C 函数调用目标 C 函数,但代码在 objc_msgSend 中不断崩溃。

我的 Objective-C 类是一个单例,我正在使用以下代码。

void c_function(int arg0, const char *arg1)  
{  
   [[objc_class instance] testFunction:arg0 Arg1:arg1];  
}

gdb 显示在调用 Objective-C 函数时发生了崩溃。如何在 c 函数中调用 Objective-C 函数?

谢谢

【问题讨论】:

  • 你的意思是objective-c“方法”吗?我看不出你的代码有什么问题。你能提供更多细节吗?
  • @Gary,你知道如何从 C 调用你的 Objective-C 单例吗?

标签: c objective-c function


【解决方案1】:

您的代码没有任何问题,因为从 c 函数调用 objc 方法没有特殊规则。如果 objc_msgSend 发生崩溃,请参考http://www.sealiesoftware.com/blog/archive/2008/09/22/objc_explain_So_you_crashed_in_objc_msgSend.html。如果 objc 行位于其他 objc 代码中,也会发生同样的事情——很可能您忘记保留单例的共享实例。

【讨论】:

  • 谢谢。事实证明,问题的发生是由于使用第三方库时出现了一些内存损坏。
【解决方案2】:

[[objc_class instance] testFunction:arg0 Arg1:arg1];

由于您没有提供更多信息:

objec_class 是一个实例,你的单身?它处理消息instance? …

objec_class 真的是一个类,有一个类方法instance?这将为您提供另一个实例......

换句话说,你真的有类似的东西

@interface class2 { } -(void) testFunction:(int)count Arg1:(const char *)args; @end

@include "class2.h" @interface objc_class { } -(class2*) instance { } -(void) testFunction:(int)count Arg1:(const char *)args; @end

@include "class2.h" @interface objc_class { } +(class2*) instance; // be aware of the fact, instance (normaly) does not have // access to any instance variables!

要加入吗?

你的代码看起来不像“嘿,对象(实例)单例,我告诉你“实例”。然后我接受你的回复,并给它消息“testFunction:Arg1:”(插入了一些值)”!

(你确定你理解目标c吗?)

问候

【讨论】:

  • 你确定你理解我的问题吗? :) 我问的不是单例模式的实现,而是如何从 C 函数调用 Objective-C 函数。
【解决方案3】:

1:

@interface class2 {

}

-(void) testFunction:(int)count Arg1:(const char *)args;

@end

2:

@include "class2.h"

@interface objc_class {

}

-(class2*) instance;

@end 

3:

@include "class2.h"

@interface objc_class {

}

+(class2*) instance; // be aware of the fact, instance (normally) does not
                     // have access to any instance variables!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多