I was wondering if it's possible to call a Swift function from C++? And if YES, how? I know that we can call a C++ function from Swift but I haven't found an exact answer about this.
- 1Do you want to know if it can be done or how to do it?Captain Obvlious– Captain Obvlious2015-09-29 20:49:31 +00:00Commented Sep 29, 2015 at 20:49
- @CaptainObvlious probably both.James Parsons– James Parsons2015-09-29 20:56:15 +00:00Commented Sep 29, 2015 at 20:56
- 1I'm voting to close this question as off-topic because it will illicit simple yes or no answers which in this case are not beneficial to the community.Captain Obvlious– Captain Obvlious2015-09-29 22:09:46 +00:00Commented Sep 29, 2015 at 22:09
- 3Ok... If it's just boolean issue... Why nobody gave the right response (YES or NO ) until now? I think it's a good opportunity to learn a bit more.dede.exe– dede.exe2015-09-30 01:03:17 +00:00Commented Sep 30, 2015 at 1:03
- @CaptainObvlious I just edited the question.Nav Nav– Nav Nav2015-09-30 13:39:32 +00:00Commented Sep 30, 2015 at 13:39
1 Answer
While there’s no official way to call a Swift function directly from C, you can set up a function pointer that’s callable from C. Whether that helps you depends on your exact circumstances. For example, on Apple platforms it’s super useful for integrating with C APIs that use C callbacks (things like CFRunLoop observers).
Pasted in a below is an example sans anything Apple-ish.
Share and Enjoy — Quinn “The Eskimo!” Apple Developer Relations, Developer Technical Support, Core OS/Hardware let myEmail = "eskimo" + "1" + "@apple.com"
// main.swift private func printGreeting(modifier: UnsafePointer<CChar>) { print("Hello \(String(cString: modifier))World!") } var callbacks = SomeCLibCallbacks( printGreeting: { (modifier) in printGreeting(modifier: modifier) } ) SomeCLibSetup(&callbacks) SomeCLibTest() // SomeCLib.h #ifndef SomeCLib_h #define SomeCLib_h struct SomeCLibCallbacks { void (* _Nonnull printGreeting)(const char * _Nonnull modifier); }; typedef struct SomeCLibCallbacks SomeCLibCallbacks; extern void SomeCLibSetup(const SomeCLibCallbacks * _Nonnull callbacks); extern void SomeCLibTest(void); #endif // SomeCLib.c #include "SomeCLib.h" static SomeCLibCallbacks sCallbacks; extern void SomeCLibSetup(const SomeCLibCallbacks * callbacks) { sCallbacks = *callbacks; } extern void SomeCLibTest(void) { sCallbacks.printGreeting("Cruel "); } Source: https://forums.swift.org/t/best-way-to-call-a-swift-function-from-c/9829/2