Call a C++ function from Swift

后端 未结 1 685
傲寒
傲寒 2021-02-02 01:53

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

In someCFunction.c:

void someCFunction() {
    p         


        
相关标签:
1条回答
  • 2021-02-02 02:09

    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
    
    0 讨论(0)
提交回复
热议问题