从C调用Swift的最佳方法是什么? [英] What is the best way to call into Swift from C?
问题描述
从Swift调用C非常简单,但是我正在考虑在C中创建双向包装,因此我的C必须调用Swift函数。
Calling into C from Swift is pretty simple, however I'm looking into making a bi-directional wrapper in C, so my C has to call Swift functions.
现在,我可以通过在C中声明函数指针,并在Swift端将它们设置为在Swift中调用代码后调用我的C函数来实现。
Right now, I can do this by declaring function pointers in C, and having my C functions call them after the Swift side has set them up to call code in 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" );
}
在桥接头中包含C头文件后,可以执行以下操作在Swift端:
After including my C header file in the bridging header, I can do the following on the Swift side:
let cb: callback_t = {
someKindOfSwiftFunction()
}
callBackIntoSwift( cb )
甚至:
callBackIntoSwift {
someKindOfSwiftFunction()
}
是否有更好的方法来执行此操作,而不需要函数指针和回调?我想让C端直接调用 someKindOfSwiftFunction
……但是当我尝试应用 @convention(c)
对于函数声明,我得到的消息是该属性只能应用于类型,而不能应用于声明。
Is there a better way to do this, where function pointers and callbacks are not needed? I'd like to let the C-side call someKindOfSwiftFunction
directly … but when I try to apply @convention (c)
to function declarations I get the message that the attribute can only be applied to types, and not declarations.
例如,任何想法或代码库Github我可以看看吗?
Any ideas or codebases in e.g. Github I can take a look at?
推荐答案
目前尚无官方方法。除了名称修饰之外,Swift函数还使用了与C不同的调用约定。非官方地,如果您愿意处理比平常更多的代码破坏和编译器错误,那么有一个非官方的属性@_cdecl可以做到这一点:
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
}
然后您可以从C调用它:
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调用Swift的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!