Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a C++ function from Swift

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!

like image 330
popisar Avatar asked Nov 07 '14 15:11

popisar


People also ask

Can you call C functions from Swift?

In Swift, you can call C variadic functions, such as vasprintf(_:_:_:) , using the Swift getVaList(_:) or withVaList(_:_:) functions.

Can you use Swift and Objective-C together?

You can use Objective-C and Swift files together in a single project, no matter which language the project used originally. This makes creating mixed-language app and framework targets as straightforward as creating an app or framework target written in a single language.

Is Swift better than C?

As the performance of swift, it is 2.6x faster than Objective C and 8.4x faster than python. It got an encouraging syntax that make you write clean and consistent code. It provides improve readability and prevent errors.


1 Answers

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
like image 168
MaddTheSane Avatar answered Sep 22 '22 13:09

MaddTheSane