Swift:如何调用从dylib加载的C函数 [英] Swift: How to call a C function loaded from a dylib
问题描述
有没有一种方法可以调用从Swift的dylib加载的C函数?
Is there a way to call a C function loaded from a dylib from Swift?
这是我的 dylib 文件:
cppdemofile.cpp
cppdemofile.cpp
#include "cppdemofile.h"
int add(int a, int b) {
return a + b;
}
cppdemofile.h
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并检查:
compile to dylib and check:
nm -gU libCppDemoLibrary.dylib
0000000000000f80 T _add
...将libCppDemoLibrary.dylib
复制到~/lib
...
... copy libCppDemoLibrary.dylib
to ~/lib
...
快速程序:
@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项目中吗?
How do I call the add
function? Is it ok to use a dylib? Should I instead add these sources to my swift project?
推荐答案
可以从Swift调用add
函数,因为您
定义它与extern "C"
具有C链接.
Calling the add
function from Swift is possible because you
defined it to have C linkage with extern "C"
.
使库成为一个Swift模块(如上面的jtbandes所建议
评论)可能是更好的解决方案,
但是这是您如何使用dlsym()
从Swift返回的函数指针的方法:
Making the library a Swift module (as suggested by jtbandes in above
comments) might be the better solution,
but here is how you can use the function pointer return by dlsym()
from Swift:
首先添加
typedef int(*addFunc)(int, int);
到桥接头文件,或者定义
to the bridging header file, or alternatively define
typealias addFunc = @convention(c) (CInt, CInt) -> CInt
在Swift中.然后执行以下操作:
in Swift. Then the following works:
let handle = dlopen(path, RTLD_NOW)
if (handle != nil) {
var sym = dlsym(handle, "add")
if (sym != nil) {
let f = unsafeBitCast(sym, addFunc.self)
let result = f(12, 45)
print(result)
}
dlclose(handle)
}
当然,如果addFunc
与
加载函数的实际签名.
Of course this will crash if addFunc
does not match the
actual signature of the loaded function.
更新迅速3:
if let handle = dlopen(path, RTLD_NOW) {
if let sym = dlsym(handle, "add") {
let f = unsafeBitCast(sym, to: addFunc.self)
let result = f(12, 45)
print(result)
}
dlclose(handle)
}
这篇关于Swift:如何调用从dylib加载的C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!