游戏开发

c++与oc混编之c++中调用oc方法

2017-04-10  本文已影响233人  Jesscia_Liu

1.新建C++文件

新建hpp文件.png

2.在.hpp中实现如下代码(TestObject.hpp)

public:
void testFunction(int temp){
        c_testFunction(temp);
}

3. 创建.mm文件(LNTestObject.mm)

//C中不能直接使用self来调用OC方法,这里使用单例创建对象(调用方法前需要先创建单例)
static LNTestObject*testObject =nil;
+ (instancetype)shareInstance{
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    testObject = [[self alloc] init];
  });
  return testObject;
}

//C实现
void c_testFunction(int temp){
  [testObject c_testFunction:temp];
}

//OC实现
- (void)c_testFunction:(int)temp{
  NSLog(@"temp=%zd",temp);
}

4.创建桥接文件并在.hpp中include(TestObject-C-Interface.h)

//声明实现的C方法
void c_testFunction(int temp);

github demo 地址: https://github.com/KrystalNa/oc-c-demo

上一篇下一篇

猜你喜欢

热点阅读