C调用Objective-C的类和方法

最近有一个C提供回调接口调用Objective-c接口来传递数据的需求,研究了很久,最终通过bing的AI对话查到了需要的内容,这里记录一下,算是给基于C的IOS开发开了一个头。

在Objective-C中,你可以创建一个全局的类方法,并在C语言中通过Objective-C运行时(Runtime) 来调用这个方法。以下是一个简单的例子: // Objective-C类

@interface MyClass : NSObject

+ (void)classMethodWithArg1:(int)arg1 arg2:(int)arg2;

@end

@implementation MyClass

+ (void)classMethodWithArg1:(int)arg1 arg2:(int)arg2 {

NSLog(@"Hello, %d and %d", arg1, arg2);

}

@end

// C函数

#include

#include

void callObjectiveCClassMethod() {

Class myClass = objc_getClass("MyClass");

SEL mySelector = sel_registerName("classMethodWithArg1:arg2:");

((void (*)(id, SEL, int, int))objc_msgSend)(myClass, mySelector, 10, 20);

}

在这个例子中,callObjectiveCClassMethod是一个C语言的函数,它调用了Objective-C的类方法 classMethodWithArg1:arg2:。

另外,Objective-C的代码可以直接调用C的函数,直接引入C的头文件,不需要额外改动。

id为对象类型,int、double、long等类型也支持,字符串等类型也需要通过id对象来调用。

相关链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: