xcode 从 Swift 调用 C++ 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26805097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call a C++ function from Swift
提问by popisar
How should I call a C++ function (no classes involved) from a Swift file? I tried this:
我应该如何从 Swift 文件调用 C++ 函数(不涉及类)?我试过这个:
In someCFunction.c:
在someCFunction.c 中:
void someCFunction() {
printf("Inside the C function\n");
}
void aWrapper() {
someCplusplusFunction();
}
In someCpluplusfunction.cpp:
在someCpluplusfunction.cpp 中:
void someCplusplusFunction() {
printf("Inside the C++ function");
}
In main.swift:
在main.swift 中:
someCFunction();
aWrapper();
In Bridging-Header.h:
在Bridging-Header.h 中:
#import "someCFunction.h"
#import "someCplusplusFunction.h"
I found this answervery informative, but still I cannot make it work. Could you point me in the right direction?
我发现这个答案非常有用,但我仍然无法使它工作。你能指出我正确的方向吗?
Thanks!
谢谢!
采纳答案by MaddTheSane
What does the header look like?
标题是什么样的?
If you want to explicitly set the linking type for C-compatible functions in C++, you need to tell the C++ compiler so:
如果要在 C++ 中为 C 兼容函数显式设置链接类型,则需要告诉 C++ 编译器:
// cHeader.h
extern "C" {
void someCplusplusFunction();
void someCFunction();
void aWrapper();
}
Note that this isn't valid C code, so you'd need to wrap the extern "C"
declarations in preprocessor macros.
请注意,这不是有效的 C 代码,因此您需要将extern "C"
声明包装在预处理器宏中。
On OS X and iOS, you can use __BEGIN_DECLS
and __END_DECLS
around code you want linked as C code when compiling C++ sources, and you don't need to worry about using other preprocessor trickery for it to be valid C code.
在 OS X 和 iOS 上,您可以在编译 C++ 源代码时使用__BEGIN_DECLS
并__END_DECLS
围绕要链接为 C 代码的代码,并且您无需担心使用其他预处理器技巧使其成为有效的 C 代码。
As such, it would look like:
因此,它看起来像:
// cHeader.h
__BEGIN_DECLS
void someCplusplusFunction();
void someCFunction();
void aWrapper();
__END_DECLS
EDIT: As ephemer mentioned, you can use the following preprocessor macros:
编辑:正如 ephemer 提到的,您可以使用以下预处理器宏:
// cHeader.h
#ifdef __cplusplus
extern "C" {
#endif
void someCplusplusFunction();
void someCFunction();
void aWrapper();
#ifdef __cplusplus
}
#endif