如何将c ++和Python与SWIG集成

Ran*_*ngh 2 c++ python linux django

可能重复:
集成Python和C++

我是python GUY,在django做网络的东西.我想知道使用SWIG集成python和C++是多么容易或多难.

是否有效/容易做或应该离开C++并在python中编写代码.

有一些C++文件已被过去的程序员编码.我知道SWIG用于集成语言,但我不知道使用它有什么实际意义或问题.

或者没有使用它,在Python中重写代码是更好的选择.

log*_*og0 6

使用swig很容易.通常比人们想象的容易.见http://www.swig.org/tutorial.html.

基本上你只需编写一个接口文件*.i,它只包含你需要的标题.
example.i:

 %module example
  %{
  /* Includes the header in the wrapper code */
  #include "header.h"
  %}

  /* Parse the header file to generate wrappers */
  %include "header.h"
Run Code Online (Sandbox Code Playgroud)

然后使用SWIG生成包装器.用你的c ++代码编译它就完成了:

$ swig -python example.i
$ g++ -c example.cc example_wrap.cc \
    -I/usr/local/include/python2.1
$ ld -shared example.o example_wrap.o -o _example.so
Run Code Online (Sandbox Code Playgroud)

你得到了你的python模块.

>>> import example
>>> example.foo()
Run Code Online (Sandbox Code Playgroud)