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)