Call cpp

  1. Start xcode

  2. Create a new project, macOS -> Command Line Tool

  3. Product name: TestCpp

  4. Language Swift

  5. Edit main.swift, keep only println("hello world") and remove other lines

  6. Product -> Run

  7. Create a c++ shared library

./code/call_cpp/hello.h
class A {
public:
  A(int);
  int getInt() const;

private:
  int i_;
};
./code/call_cpp/hello.cc
#include "hello.h"

A::A(int k) : i_(k) {}
int A::getInt() const { return i_; }
./code/call_cpp/Makefile
all: libhello.a

libhello.a: hello.h hello.cc
	g++ -c hello.cc -o hello.o
	ar r libhello.a hello.o

clean:
	$(RM) libhello.a hello.o
  1. In xcode, project->build phases->frameworks and libraries, click +, and select libhello.a. Then, modify build settings to change the library search paths (in search paths)

  2. Add hello.h to the same folder of main.swfit. File->Add files to TestCpp.

  3. Add a wrapper. File->New->File->C++ file, next, choose an arbitrary name, e.g., wrapper.cc. Uncheck Also create a header file. We only need the .cc file. In the popped-up dialog, select Create bridging header.

  4. If we don't select Create bridging header, we have to go to build settings, swift compiler, objective-c bridging header, and enter a header name.

  5. Content of wrapper.cc

#include "hello.h"
extern "C" int getIntFromCpp() {
    return A(10).getInt();
}
  1. Content of the bridging header TestCpp-Briding-Header.h:

int getIntFromCpp();
  1. In main.swift, use print(getIntFromCpp())