C调用Objective-C的类和方法

C调用Objective-C的类和方法

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

在Objective-C中,你可以创建一个全局的类方法,并在C语言中通过Objective-C运行时(Runtime)

来调用这个方法。以下是一个简单的例子:

// Objective-C类

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函数

c 复制代码
#include <objc/runtime.h>
#include <objc/message.h>
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对象来调用。

相关推荐
HarderCoder2 小时前
iOS 知识积累第一弹:从 struct 到 APP 生命周期的全景复盘
ios
叽哥12 小时前
Flutter Riverpod上手指南
android·flutter·ios
用户092 天前
SwiftUI Charts 函数绘图完全指南
ios·swiftui·swift
YungFan2 天前
iOS26适配指南之UIColor
ios·swift
权咚2 天前
阿权的开发经验小集
git·ios·xcode
用户092 天前
TipKit与CloudKit同步完全指南
ios·swift
法的空间2 天前
Flutter JsonToDart 支持 JsonSchema
android·flutter·ios
2501_915918413 天前
iOS 上架全流程指南 iOS 应用发布步骤、App Store 上架流程、uni-app 打包上传 ipa 与审核实战经验分享
android·ios·小程序·uni-app·cocoa·iphone·webview
小莞尔3 天前
【51单片机】【protues仿真】基于51单片机的篮球计时计分器系统
c语言·stm32·单片机·嵌入式硬件·51单片机
小莞尔3 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机