小编Aja*_*jay的帖子

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

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 …
Run Code Online (Sandbox Code Playgroud)

c++ python swig

10
推荐指数
2
解决办法
1万
查看次数

标签 统计

c++ ×1

python ×1

swig ×1