python是解釋性語言, 底層就是用c實作的, 是以用python調用c是很容易的, 下面就總結一下各種調用的方法, 給出例子, 所有例子都在ubuntu9.10, python2.6下試過.
1. python 調用 c (base)
想在python中調用c函數, 如這兒的fact
#include
int fact(int n)
{
if (n <= 1)
return 1;
else
return n * fact(n - 1);
}
pyobject* wrap_fact(pyobject* self, pyobject* args)
int n, result;
if (! pyarg_parsetuple(args, "i:fact", &n))
return null;
result = fact(n);
return py_buildvalue("i", result);
static pymethoddef examplemethods[] =
{"fact", wrap_fact, meth_varargs, "caculate n!"},
{null, null}
};
void initexample()
pyobject* m;
m = py_initmodule("example", examplemethods);
把這段代碼存為wrapper.c, 編成so庫,
gcc -fpic wrapper.c -o example.so -shared -i/usr/include/python2.6 -i/usr/lib/python2.6/config
然後在有此so庫的目錄, 進入python, 可以如下使用
import example
example.fact(4)
2. python 調用 c++ (base)
在python中調用c++類成員函數, 如下調用testfact類中的fact函數,
class testfact{
public:
testfact(){};
~testfact(){};
int fact(int n);
int testfact::fact(int n)
return n * (n - 1);
testfact t;
return t.fact(n);
extern "c" //不加會導緻找不到initexample
把這段代碼存為wrapper.cpp, 編成so庫,
g++ -fpic wrapper.cpp -o example.so -shared -i/usr/include/python2.6 -i/usr/lib/python2.6/config
3. python 調用 c++ (boost.python)
boost庫是非常強大的庫, 其中的python庫可以用來封裝c++被python調用, 功能比較強大, 不但可以封裝函數還能封裝類, 類成員.
http://dev.gameres.com/program/abstract/building%20hybrid%20systems%20with%20boost_python.chn.by.jerry.htm
首先在ubuntu下安裝boost.python, apt-get install libboost-python-dev
char const* greet()
return "hello, world";
boost_python_module(hello)
using namespace boost::python;
def("greet", greet);
把代碼存為hello.cpp, 編譯成so庫
g++ hello.cpp -o hello.so -shared -i/usr/include/python2.5 -i/usr/lib/python2.5/config -lboost_python-gcc42-mt-1_34_1
此處python路徑設為你的python路徑, 并且必須加-lboost_python-gcc42-mt-1_34_1, 這個庫名不一定是這個, 去/user/lib查
>>> import hello
>>> hello.greet()
'hello, world'
4. python 調用 c++ (ctypes)
ctypes allows to call functions in dlls/shared libraries and has extensive facilities to create, access and manipulate simple and complicated c data types in python - in other words: wrap libraries in pure python. it is even possible to implement c callback functions in pure python.
http://python.net/crew/theller/ctypes/
extern "c"
将代碼存為wrapper.cpp不用寫python接口封裝, 直接編譯成so庫,
g++ -fpic wrapper.cpp -o example.so -shared -i/usr/include/python2.6 -i/usr/lib/python2.6/config
進入python, 可以如下使用
>>> import ctypes
>>> pdll = ctypes.cdll('/home/ubuntu/tmp/example.so')
>>> pdll.fact(4)
12
本文章摘自部落格園,原文釋出日期:2011-07-05