0%

How to call C/C++ code from Python

這篇文章正好是上一篇的相反行為。為了加速某些特殊運算,有時需要呼叫C/C++的程式碼。使用Python內建的ctypes可以幫助完成這件事。

lang: cpp foo.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

class Foo {
public:
void bar() {
std::cout << "Hello" << std::endl;
}
};

extern "C" {
Foo* Foo_new(){ return new Foo(); }
void Foo_bar(Foo* foo) { foo->bar(); }
}

將其編譯成Shared Library / DLL。

1
2
$ g++ -c -fPIC foo.cpp -o foo.o
$ g++ -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o

接著就是Python code上場了

1
2
3
4
5
6
7
8
9
10
11
12
from ctypes import cdll
lib = cdll.LoadLibrary('./libfoo.so')

class Foo(object):
def __init__(self):
self.obj = lib.Foo_new()

def bar(self):
lib.Foo_bar(self.obj)

f = Foo()
f.bar() #and you will see "Hello" on the screen

Windows版跟Linux版大同小異,最大的差別在於Windows可以寫 ./libfoo 而不用寫 ./libfoo.dll:而 Linux沒有附檔名的話會發生錯誤。

當然,swigBoost Python一樣可以幫忙完成這件事。