从 C 调用 Swift 的最佳方式是什么? [英] What is the best way to call into Swift from C?
问题描述
从 Swift 调用 C 非常简单,但是我正在考虑在 C 中制作一个双向包装器,所以我的 C 必须调用 Swift 函数.
现在,我可以通过在 C 中声明函数指针,并在 Swift 端设置它们以在 Swift 中调用代码后让我的 C 函数调用它们来实现这一点.
我的 C 头文件:
typedef void (*callback_t)(void);void callBackIntoSwift( callback_t cb );
我的 C 实现文件:
#include "stuff.h"#include void callBackIntoSwift( callback_t cb ){printf( "将回调到 Swift
" );cb();printf( "确实回调到 Swift
" );}
在桥接头中包含我的 C 头文件后,我可以在 Swift 端执行以下操作:
let cb: callback_t = {someKindOfSwiftFunction()}callBackIntoSwift( cb )
甚至:
callBackIntoSwift {someKindOfSwiftFunction()}
在不需要函数指针和回调的情况下,有没有更好的方法来做到这一点?我想让 C 端直接调用 someKindOfSwiftFunction
……但是当我尝试将 @convention (c)
应用于函数声明时,我得到消息,该属性可以仅适用于类型,而不适用于声明.
任何想法或代码库,例如Github我可以看看吗?
根据 Joe Groff:
<块引用>目前还没有正式的方法.除了名称修改之外,Swift 函数使用与 C 不同的调用约定.非正式地,如果您愿意处理比通常数量更多的代码损坏和编译器错误,那么有一个非官方属性 @_cdecl 可以做到这一点:
@_cdecl("mymodule_foo")func foo(x: Int) ->整数{返回 x * 2}
<块引用>
然后你可以从 C: 调用它
#include intptr_t mymodule_foo(intptr_t);intptr_t invoke_foo(intptr_t x) {返回 mymodule_foo(x);}
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.
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.
My C header file:
typedef void (*callback_t)(void);
void callBackIntoSwift( callback_t cb );
My C implementation file:
#include "stuff.h"
#include <stdio.h>
void callBackIntoSwift( callback_t cb )
{
printf( "Will call back into Swift
" );
cb();
printf( "Did call back into 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 )
Or even:
callBackIntoSwift {
someKindOfSwiftFunction()
}
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.
Any ideas or codebases in e.g. Github I can take a look at?
According to 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 调用 Swift 的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!