c - 从 C 调用 Swift 的最佳方式是什么?

标签 c swift callback wrapper

从 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/

相关文章:

c++ - 转到优化重构

c# - 这行 C 代码在 C# 中相当于什么?

swift - 错误的元素出现在 Firebase querySnapshot 中

node.js - Node : force callback execution if method hangs

c# - 异步 ServiceStack Web 服务调用后回调以更新 GUI

c - struct tab 中的 INT 需要 malloc 吗?

ios - 起始选项卡 - UITabBarController Swift iOS

ios - Swift & Couchbase Lite 发出函数导致 EXC_BAD_ACCESS(代码 = 2)

c - 如何使用回调修改 GtkWidget 数组的元素

c - 0[str] 在 C 中意味着什么,其中 str 是字符串