2010-08-07 106 views
2

我想从C函数调用一个Objective-C函数,但代码在objc_msgSend中不断崩溃。如何从C函数调用objective-C函数

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

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

当调用objective-C函数时,gdb显示崩溃正在发生。如何从c函数中调用一个Objective-C函数?

感谢

+0

你的意思是objective-c“方法”吗?我看不出你的代码有什么问题。你能提供更多细节吗? – yehnan 2010-08-07 00:13:38

+0

@Gary,你知道怎么从C调用你的Objective-C单例吗? – user2924482 2016-09-09 23:42:23

回答

2

没有什么不对您的代码有调用C函数objc方法并没有硬性规定。如果objc_msgSend发生崩溃,请参阅http://www.sealiesoftware.com/blog/archive/2008/09/22/objc_explain_So_you_crashed_in_objc_msgSend.html。如果objc行在其他objc代码中也会发生同样的事情 - 很可能您忘记保留单例的共享实例。

+0

谢谢。事实证明这个问题是由于第三方库的使用中存在内存损坏而发生的。 – Gary 2010-08-08 23:03:16

-1

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

由于你没有提供进一步的信息:

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

objec_class真的是一类,具有类方法实例?这会给你另一个实例...

换句话说,你真的有这样的事

@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?)

问候

+0

你确定你理解我的问题吗? :)我没有问单独模式实现,而是关于如何从C函数调用objective-C函数。 – Gary 2010-08-08 23:04:56

-1

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!