Call cpp
Start xcode
Create a new project, macOS -> Command Line Tool
Product name: TestCpp
Language Swift
Edit
main.swift
, keep onlyprintln("hello world")
and remove other linesProduct -> Run
Create a c++ shared library
class A {
public:
A(int);
int getInt() const;
private:
int i_;
};
#include "hello.h"
A::A(int k) : i_(k) {}
int A::getInt() const { return i_; }
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
In xcode, project->build phases->frameworks and libraries, click
+
, and selectlibhello.a
. Then, modify build settings to change the library search paths (in search paths)Add
hello.h
to the same folder ofmain.swfit
. File->Add files toTestCpp
.Add a wrapper. File->New->File->C++ file, next, choose an arbitrary name, e.g.,
wrapper.cc
. UncheckAlso create a header file
. We only need the.cc
file. In the popped-up dialog, selectCreate bridging header
.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.Content of
wrapper.cc
#include "hello.h"
extern "C" int getIntFromCpp() {
return A(10).getInt();
}
Content of the bridging header
TestCpp-Briding-Header.h
:
int getIntFromCpp();
In
main.swift
, useprint(getIntFromCpp())