Calling a swift framework from c or cpp code?

Hello There,


I am researching if it is feasible to create a swift framework, and build an assembly from it, then reference it and use it from c or cpp code.

If anybody has any experience with this, or could lead me to an article/forum post etc, that would be great!


Cheers,

vk_

Accepted Reply

I don't know if this works with C/C++ (it was designed to work with Obj-C), but all Swift modules contain a header for compatibility with the traditional header importing system:

#import "ModuleName-Swift.h" //If you're not using modules

Replies

I don't know if this works with C/C++ (it was designed to work with Obj-C), but all Swift modules contain a header for compatibility with the traditional header importing system:

#import "ModuleName-Swift.h" //If you're not using modules

Thanks, this confirms my findings!

In addition you can wrap objective-c with cpp and call it from whereever you want to.

But does it work? I'm really interested to hear if it actually works in C/C++

I'll set up a sample project in the upcoming days and will let you know!

HI, I'm curious whether you got this working? We have a pure Swift 3.1 module we've been developing, and we're considering calling it from a cross-platform app built with Juce 5 (C++ library for audio/music apps). It seems like it should be possible, but just curious if anyone knows for certain.


Thanks in advance.


J.

On an Apple platform? If so, this should be relatively straightforward. You should give it a try with a test project and see how you get along.

I tried it here in my office and didn’t encounter any significant difficulties. My main problem was that I had to remember to mark all the Swift APIs as

public
(-:

Here’s my Swift code from the framework:

import Foundation

public class Fff : NSObject {
    public func test() {
        NSLog("Fff.test()")
    }
}

And here’s the app’s Objective-C code calling it:

@import MyFramework;

…
[[[Fff alloc] init] test];
…

As a practical measure you may want to export your Swift APIs as Objective-C, because the interoperability story there is really nice. If you then want to call it from C++ you can use Objective-C++ to gateway through.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Okay, so the basic approach is to leverage Swift/ObjC++ interop.

Makes sense.


Thanks,


J.