【发布时间】:2016-04-12 17:13:14
【问题描述】:
有没有办法从 Swift 调用从 dylib 加载的 C 函数?
这是我的 dylib 文件:
cppdemofile.cpp
#include "cppdemofile.h"
int add(int a, int b) {
return a + b;
}
cppdemofile.h
#ifndef __CppDemoLibrary__cppdemofile__
#define __CppDemoLibrary__cppdemofile__
#pragma GCC visibility push(default)
extern "C" int add(int a, int b);
#pragma GCC visibility pop
#endif
编译到dylib并检查:
nm -gU libCppDemoLibrary.dylib
0000000000000f80 T _add
...复制libCppDemoLibrary.dylib 到~/lib...
Swift 程序:
@IBAction func buttonClick(sender: NSButton) {
let handle = dlopen("libCppDemoLibrary.dylib", RTLD_NOW)
if (handle != nil) {
var sym = dlsym(handle, "add")
if (sym != nil) {
let pointer = UnsafeMutablePointer<(CInt, CInt) -> CInt>(sym)
// When debugging, I'm reaching up to this point...
// but now, how do I call the 'add' function here???
// var result = ???
// label.stringValue = "Total: " + String(result)
}
}
}
如何调用add 函数?使用dylib可以吗?我应该将这些来源添加到我的 swift 项目中吗?
【问题讨论】:
-
1.为什么是迪尔德? 2. 你有没有试过把它做成一个模块并从 Swift 中导入?
-
问题标题有点误导,因为
add有C链接。你不能从 Swift 调用 C++ 函数。