使用SWIG在Python中包装C++类

Aja*_*jay 10 c++ python swig

example.h:

#ifndef EXAMPLE_H
#define EXAMPLE_H

class Math {
 public:
    int pi() const;
    void pi(int pi);
 private:
    int _pi;
};

#endif
Run Code Online (Sandbox Code Playgroud)

example.cpp:

#include "example.h"

int Math::pi() const {
    return this->_pi;
}  
void Math::pi(int pi) {
    this->_pi = pi;
}
Run Code Online (Sandbox Code Playgroud)

example.swig:

%module example
%{ 
    #define SWIG_FILE_WITH_INIT
    #include "example.h"
%}
%include "example.h"
Run Code Online (Sandbox Code Playgroud)

然后我使用以下命令生成包装器"example.py"和"example_wrap.c":

swig  -python example.swig
Run Code Online (Sandbox Code Playgroud)

当我尝试使用以下代码编译包装类时:

g++ -fPIC -c example.cpp example_wrap.c -I/usr/local/include/python2.6/
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

example_wrap.cpp: In function "PyObject* Swig_var_Math_get()":
example_wrap.cpp:2725: error: expected primary-expression before "void"
example_wrap.cpp:2725: error: expected ")" before "void"
Run Code Online (Sandbox Code Playgroud)

错误位于以下行:

pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(&Math), SWIGTYPE_p_class,  0 );

#define SWIG_as_voidptr(a) (void *)((const void *)(a))
Run Code Online (Sandbox Code Playgroud)

它是生成包装类"example_wrap.c"的正确方法吗?

Chr*_*ard 13

我认为swig命令应该是"swig -c ++ -python example.swig"


zwo*_*wol 5

这里没有足够的信息来确定什么是错的,但我对你可以尝试的事情有两个想法.

  1. 您的g++调用正在编译C源文件,就像它是C++一样.这保证有效.试试吧

    gcc -I/usr/local/include/python2.6 -fPIC -c example_wrap.c
    gcc -I/usr/local/include/python2.6 -fPIC -c example.cpp
    g++ -shared example_wrap.o example.o -o example.so
    
    Run Code Online (Sandbox Code Playgroud)

    (是的,srsly,只使用g ++作为链接)

  2. 如果这不起作用,编译example_wrap.c如下:

    gcc -I/usr/local/include/python2.6 -fPIC -c -save-temps example_wrap.c
    
    Run Code Online (Sandbox Code Playgroud)

这将以相同的方式失败,但会生成一个名为example_wrap.i"预处理"结果的文件.这将是巨大的.在该文件中搜索该函数Swig_var_Math_get,并在该问题中添加该函数的完整文本(但没有其他内容).