从 Swift 调用 C 非常简单,但是我正在考虑在 C 中制作一个双向包装器,所以我的 C 必须调用 Swift 函数。
现在,我可以通过在 C 中声明函数指针,并让我的 C 函数在 Swift 端将它们设置为在 Swift 中调用代码后调用它们来实现这一点。
我的 C 头文件:
typedef void (*callback_t)(void);
void callBackIntoSwift( callback_t cb );
我的 C 实现文件:
#include "stuff.h"
#include <stdio.h>
void callBackIntoSwift( callback_t cb )
{
printf( "Will call back into Swift\n" );
cb();
printf( "Did call back into Swift\n" );
}
在桥接 header 中包含我的 C header 文件后,我可以在 Swift 端执行以下操作:
let cb: callback_t = {
someKindOfSwiftFunction()
}
callBackIntoSwift( cb )
甚至:
callBackIntoSwift {
someKindOfSwiftFunction()
}
有没有更好的方法来做到这一点,不需要函数指针和回调?我想让 C 端直接调用 someKindOfSwiftFunction
……但是当我尝试将 @convention (c)
应用于函数声明时,我得到的消息是属性可以仅适用于类型,不适用于声明。
任何想法或代码库,例如Github我可以看看吗?
最佳答案
根据 Joe Groff :
There’s no official way yet. Aside from name mangling, Swift functions use a different calling convention from C. Unofficially, if you’re willing to deal with more than the usual amount of code breakage and compiler bugs, there’s an unofficial attribute @_cdecl that does this:
@_cdecl("mymodule_foo")
func foo(x: Int) -> Int {
return x * 2
}
which you can then call from C:
#include <stdint.h>
intptr_t mymodule_foo(intptr_t);
intptr_t invoke_foo(intptr_t x) {
return mymodule_foo(x);
}
关于c - 从 C 调用 Swift 的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35106118/