在swift中调用C/C++代码

swift可以直接调用C代码,但无法直接调用C++代码,调用C++代码需要通过OC中转

Swift调用C代码

File->New->Files 选择新建C 文件,文件名选择hello_c,首次创建C文件,会自动提示创建Bridging Header

示例代码如下:

// hello_c.h

#ifndef hello_c_h
#define hello_c_h

#include <stdio.h>

int AddInt(int a, int b);

#endif /* hello_c_h */

// hello_c.c
#include "hello_c.h"

int AddInt(int a, int b) {
  printf("sum is %d", a+b);
  return a+b;
}

// mix_demo-Bridging-Header.h
#import "hello_c.h"

// **.swift
// 直接调用即可,运行输出"sum is 15"
var sum = AddInt(7, 8)

Swift调用C++代码

File->New->Files 选择新建Cocoa Touch Class文件,文件名输入HelloWrapper

// mix_demo-Bridging-Header.h
#import "HelloWrapper.h"

// HelloWrapper.h
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface HelloWrapper : NSObject

-(NSString*) getVersion;

@end

NS_ASSUME_NONNULL_END

// 修改HelloWrapper.m文件为HelloWrapper.mm
#import "HelloWrapper.h"
#include <string>

// 添加的c++函数
std::string GetVersion() {
  return "version from cpp";
}

@implementation HelloWrapper

-(NSString*) getVersion {
  std::string version = GetVersion();
  NSLog(@"%s", version.c_str());
  return [NSString stringWithUTF8String: version.c_str()];
}

@end

// **.swift
// 直接调用即可,运行输出"version from cpp"
var version = HelloWrapper().getVersion()

示例代码github地址

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Index