Call a C++ function from Swift

雨燕双飞 提交于 2019-12-20 10:04:45

问题


How should I call a C++ function (no classes involved) from a Swift file? I tried this:

In someCFunction.c:

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

void aWrapper() {
    someCplusplusFunction();
}

In someCpluplusfunction.cpp:

void someCplusplusFunction() {
    printf("Inside the C++ function");
}

In main.swift:

someCFunction();
aWrapper();

In Bridging-Header.h:

#import "someCFunction.h"
#import "someCplusplusFunction.h"

I found this answer very informative, but still I cannot make it work. Could you point me in the right direction?

Thanks!


回答1:


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:

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

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.

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:

// cHeader.h

#ifdef __cplusplus 
extern "C" { 
#endif 
void someCplusplusFunction();
void someCFunction();
void aWrapper();
#ifdef __cplusplus 
}
#endif


来源:https://stackoverflow.com/questions/26805097/call-a-c-function-from-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!