Can I mix Swift with C++? Like the Objective-C .mm files

C++Objective CSwift

C++ Problem Overview


I just changed my .m files to .mm and use C++. Is there a way to do the same with Swift?

C++ Solutions


Solution 1 - C++

The confusion may come from the assumption that merely changing a file extension from .m to .mm is all you need to bridge the languages, when, in reality, it does nothing of that sort. It is not the .mm that causes friction with .cpp, it is the .h header which must positively not be a C++ header.


Same project: Yes.

In the same project, you can happily mix C, C++, Objective-C, Objective C++, Swift, and even Assembly.

  1. ...Bridging-Header.h: you expose C, Objective-C and Objective-C++ to Swift using this bridge
  2. <ProductModuleName>-Swift.h: exposes automatically your Swift classes marked with @objc to Objective-C
  3. .h: this is the tricky part, since they are ambiguously used for all flavors of C, ++ or not, Objective or not. When a .h does not contain a single C++ keyword, like class, it can be added to the ...Bridging-Header.h, and will expose whatever function the corresponding .c or .cpp functionalities it declares. Otherwise, that header must be wrapped in either a pure C or Objective-C API.

Same file: No.

In the same file, you can't mix all 5. In the same source file:

  1. .swift: you can't mix Swift with anything
  2. .m: you can mix Objective-C with C. (@Vinzzz)
  3. .mm: you can mix Objective-C with C++. This bridge is Objective-C++. (@Vinzzz).
  4. .c: pure C
  5. .cpp: you can mix C++ & Assembly (@Vality)
  6. .h: ubiquitous and ambiguous C, C++, Objective-C or Objective-C++, so the answer is it depends.

References

Solution 2 - C++

No. When you switch from .m to .mm you are actually switching from Objective-C to a different language (which has many subtle differences) called Objective-C++. So you're not really using C++; you're using Objective-C++ which accepts most C++ as input (in the same way that C++ accepts most but not all C as input). When I say it's not quite C++, consider a C++ file that includes a variable named nil (which is legal C++) and then try to compile that as Objective-C++.

Swift doesn't have the same relationship. It is not a superset of C or C++, and you can't directly use either in a .swift file.

"Using Swift with Cocoa and Objective-C" also tells us:

>You cannot import C++ code directly into Swift. Instead, create an Objective-C or C wrapper for C++ code.

Solution 3 - C++

I wrote a simple Xcode 6 project that show how to mix C++, Objective C and Swift code:

https://github.com/romitagl/shared/tree/master/C-ObjC-Swift/Performance_Console

In particular the example call an Objective C and a C++ function from the Swift.

The key is to create a shared header Project-Bridging-Header.h and put the Objective C headers there.

Please download the project as a complete example.

Solution 4 - C++

You can also skip the Objective-C file in between. Just add a C header file with a .cpp source file. Have only C declarations in the header file and include any C++ code in the source file. Then include the C header file in the **-Bridging-Header.h.

The following example returns a pointer to a C++ object (struct Foo) so Swift can store in a COpaquePointer instead of having struct Foo defined in the global space.

Foo.h file (seen by Swift - included in the bridging file)

#ifndef FOO_H
#define FOO_H

// Strictly C code here.
// 'struct Foo' is opaque (the compiler has no info about it except that 
// it's a struct we store addresses (pointers) to it.
struct Foo* foo_create();
void foo_destroy(struct Foo* foo);

#endif

Inside source file Foo.cpp (not seen by Swift):

extern "C"
{
#include "Foo.h"
}
#include <vector>

using namespace std;

// C++ code is fine here. Can add methods, constructors, destructors, C++ data members, etc.
struct Foo
{
   vector<int> data;
};

struct Foo* foo_create()
{
   return new Foo;
}

void foo_destroy(struct Foo* foo)
{
    delete foo;
}

Solution 5 - C++

I have just made a little example project using Swift, Objective-C and C++. It's a demo of how to use OpenCV stitching in iOS. The OpenCV API is C++ so we can't talk to it directly from Swift. I use a small wrapper class who's implementation file is Objective-C++. The Header file is clean Objective-C, so Swift can talk to this directly. You have to take care not to indirectly import any C++-ish files into the the headers that Swift interacts with.

The project is here: https://github.com/foundry/OpenCVSwiftStitch

Solution 6 - C++

Here's my attempt at a clang tool to automate C++/swift communication. You can instanciate C++ classes from swift, inherit from C++ class and even override virtual methods in swift.
It will parse the C++ class you want to export to swift and generate the Objective-C/Objective-C++ bridge automatically.

https://github.com/sandym/swiftpp

Solution 7 - C++

Swift is not directly compatible with C++. You can work around the issue by wrapping your C++ code with Objective-C, and using the Objective C wrapper in Swift.

Solution 8 - C++

I also have a demo program for swift combining opencv.

You can download it from https://github.com/russj/swift_opencv3_demo.

More information about the demo http://flopalm.com/opencv-with-swift/.

Solution 9 - C++

No, not in a single file.

However, you may use C++ in Swift Projects without needing a static library or framework. Like others have said, the key is to make an Objective-C bridging header that #includes C-compatible C++ headers that are marked as C compatible with the extern "C" {} trick.

Video tutorial: https://www.youtube.com/watch?v=0x6JbiphNS4

Solution 10 - C++

Other answers are slightly inaccurate. You can actually mix both Swift and [Objective-]C[++] in the same file, though not quite the way you would expect.

This file (c.swift) compiles to a valid executable with both swiftc c.swift and clang -x objective-c c.swift

/* /* */
#if 0
// */
import Foundation
print("Hello from Swift!")
/* /* */
#endif
#include <stdio.h>
int main()
{
    puts("Hello from C!");
    return 0;
}
// */

Solution 11 - C++

One trick (of many) is that

You need a separate header for your bridging obj-c++ file...

You can't just throw @interface and @implementation in the same .mm file as one often does normally.

So in your bridging header file you have

#import "Linkage.hpp"

Linkage.hpp has the @interface for Linkage and Linkage.mm has the @implementation for .mm

And then

...you actually don't #include "yourCpp.hpp" in Linkage.hpp.

You only put #include "yourCpp.hpp" in the Linkage.mm file, not in the Linkage.hpp file.

In many online examples/tutorials, the writer simply puts the @interface and @implementation in the same .mm file, as one often does.

That will work in very simple cpp bridging examples, but,

The problem is:

if your yourCpp.hpp has any c++ features at all which it surely will (like, the first line #include <something>), then the process will fail.

But if you just don't have the #include "yourCpp.hpp" in the Linkage header file (it's fine to have it in the .mm file, obviously you'll need to) - it works.

Again this is unfortunately just one tip in the whole process.

Solution 12 - C++

In case this is helpful to anyone, I also have a brief tutorial on calling a simple C++ static library from a trivial Swift command line utility. This is a really bare-bones proof of concept piece of code.

No Objective-C involved, just Swift and C++. Code in a C++ library is called by a C++ wrapper that implements a function with extern "C" linkage. That function is then referenced in the bridging header and called from Swift.

See http://www.swiftprogrammer.info/swift_call_cpp.html

Solution 13 - C++

I am providing a link to SE-0038 in the official resource, described as This maintains proposals for changes and user-visible enhancements to the Swift Programming Language.

The status as of today is that this is the feature request which has been accepted but not yet scheduled.

This link is intended to steer anyone looking for this feature in the right direction

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEhTdView Question on Stackoverflow
Solution 1 - C++SwiftArchitectView Answer on Stackoverflow
Solution 2 - C++Rob NapierView Answer on Stackoverflow
Solution 3 - C++Gian Luigi RomitaView Answer on Stackoverflow
Solution 4 - C++Dan GView Answer on Stackoverflow
Solution 5 - C++foundryView Answer on Stackoverflow
Solution 6 - C++SandyView Answer on Stackoverflow
Solution 7 - C++AustinView Answer on Stackoverflow
Solution 8 - C++RussjView Answer on Stackoverflow
Solution 9 - C++James MartView Answer on Stackoverflow
Solution 10 - C++archoView Answer on Stackoverflow
Solution 11 - C++FattieView Answer on Stackoverflow
Solution 12 - C++Anatoli PView Answer on Stackoverflow
Solution 13 - C++Ryan HeitnerView Answer on Stackoverflow