从Swift调用C++函数

pop*_*sar 9 c c++ xcode linker swift

我应该如何从Swift文件中调用C++函数(不涉及类)?我试过这个:

someCFunction.c中:

void someCFunction() {
    printf("Inside the C function\n");
}

void aWrapper() {
    someCplusplusFunction();
}
Run Code Online (Sandbox Code Playgroud)

someCpluplusfunction.cpp中:

void someCplusplusFunction() {
    printf("Inside the C++ function");
}
Run Code Online (Sandbox Code Playgroud)

main.swift中:

someCFunction();
aWrapper();
Run Code Online (Sandbox Code Playgroud)

Bridging-Header.h中:

#import "someCFunction.h"
#import "someCplusplusFunction.h"
Run Code Online (Sandbox Code Playgroud)

我发现这个答案非常有用,但我仍然无法使其发挥作用.你能指出我正确的方向吗?

谢谢!

Mad*_*ane 10

标题是什么样的?

如果要在C++中为C兼容函数显式设置链接类型,则需要告诉C++编译器:

// cHeader.h

extern "C" {
    void someCplusplusFunction();
    void someCFunction();
    void aWrapper();
}
Run Code Online (Sandbox Code Playgroud)

请注意,这不是有效的C代码,因此您需要extern "C"在预处理器宏中包装声明.

在OS X和iOS上,您可以在编译C++源代码时使用__BEGIN_DECLS__END_DECLS围绕要作为C代码链接的代码,并且您不必担心使用其他预处理器技巧来使其成为有效的C代码.

因此,它看起来像:

// cHeader.h

__BEGIN_DECLS
void someCplusplusFunction();
void someCFunction();
void aWrapper();
__END_DECLS
Run Code Online (Sandbox Code Playgroud)

编辑:正如ephemer所提到的,您可以使用以下预处理器宏:

// cHeader.h

#ifdef __cplusplus 
extern "C" { 
#endif 
void someCplusplusFunction();
void someCFunction();
void aWrapper();
#ifdef __cplusplus 
}
#endif
Run Code Online (Sandbox Code Playgroud)

  • "你需要在预处理器宏中包装`extern"C"`声明",特别是:`#ifdef __cplusplus extern"C"{#endif`你的C函数定义在这里......`#ifdef __cplusplus} #endif` .我不能在评论中添加换行符,但是你需要在"extern C {"和"}"之前和之后换行符 (2认同)