从C ++调用Swift函数 [英] Calling a Swift function from C++
问题描述
我想知道是否可以从C ++调用Swift函数?如果是的话,怎么办?我知道我们可以从Swift调用C ++函数,但是我还没有找到确切的答案.
I was wondering if it's possible to call a Swift function from C++? And if YES, how? I know that we can call a C++ function from Swift but I haven't found an exact answer about this.
推荐答案
虽然没有正式的方法可以直接从C调用Swift函数,但是您可以设置一个可以从C调用的函数指针.是否可以帮助您取决于您的确切情况.例如,在Apple平台上,与使用C回调(例如CFRunLoop观察器)的C API集成非常有用.
While there’s no official way to call a Swift function directly from C, you can set up a function pointer that’s callable from C. Whether that helps you depends on your exact circumstances. For example, on Apple platforms it’s super useful for integrating with C APIs that use C callbacks (things like CFRunLoop observers).
以下示例中粘贴了一个没有Apple风格的示例.
Pasted in a below is an example sans anything Apple-ish.
分享并享受-奎因爱斯基摩人!"Apple开发人员关系,开发人员技术支持,核心操作系统/硬件让myEmail ="eskimo"+"1"+"@ apple.com"
Share and Enjoy — Quinn "The Eskimo!" Apple Developer Relations, Developer Technical Support, Core OS/Hardware let myEmail = "eskimo" + "1" + "@apple.com"
// main.swift
private func printGreeting(modifier: UnsafePointer<CChar>) {
print("Hello \(String(cString: modifier))World!")
}
var callbacks = SomeCLibCallbacks(
printGreeting: { (modifier) in
printGreeting(modifier: modifier)
}
)
SomeCLibSetup(&callbacks)
SomeCLibTest()
// SomeCLib.h
#ifndef SomeCLib_h
#define SomeCLib_h
struct SomeCLibCallbacks {
void (* _Nonnull printGreeting)(const char * _Nonnull modifier);
};
typedef struct SomeCLibCallbacks SomeCLibCallbacks;
extern void SomeCLibSetup(const SomeCLibCallbacks * _Nonnull callbacks);
extern void SomeCLibTest(void);
#endif
// SomeCLib.c
#include "SomeCLib.h"
static SomeCLibCallbacks sCallbacks;
extern void SomeCLibSetup(const SomeCLibCallbacks * callbacks) {
sCallbacks = *callbacks;
}
extern void SomeCLibTest(void) {
sCallbacks.printGreeting("Cruel ");
}
来源: https://forums.swift.org/t/best-way-to-call-a-swift-function-from-c/9829/2
这篇关于从C ++调用Swift函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!