Using C++ with swift

Recently I am writing an API Blueprint stubbing library in swift, and the first step is to parse the .apib file.

snowcrash is a c++ library to parse .apib and I wanted to include it as an library.

Here is what I setup for swift to call c++ static library

Xcode Settings


I assume you have compile snowcrash into an .a static library. You can find how to build on my fork on snowcrash

Other Linker Settings

In Build setting -> Other Linker Settings add -lsnowcrash

For any static c++ libraries, they will have lib prefix.

For example, if you want to use other static library called libexample.a, you can add another linker setting with -lexample

** You may want to include all .h file within library project folder.

Bridging Header

In your project you also need to add a bridging header. You can add an Objective-C class to trigger the prompt to generate a new header. Or you can add it in Build setting -> Bridging Header

C++


Add a wrapper.cpp in your project

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include "snowcrash.h"

extern "C" void snowcrashTest() {
mdp::ByteBuffer blueprint = R"(
# My API
## GET /message
+ Response 200 (text/plain)

Hello World!
)";

snowcrash::ParseResult<snowcrash::Blueprint> ast;
snowcrash::parse(blueprint, 0, ast);

std::cout << "API Name: " << ast.node.name << std::endl;

}

In your bridging header

1
void snowcrashTest();

Swift


After you add wrapper.cpp and add the function in bridging header, you can call the function directly in swift

1
2
3
4
5
6
7
import Foundation

public struct Jellyfish {
public static func printSnowcrash() {
snowcrashTest()
}
}
Share Comments