使用 SWIG 在 Python 中包装 C++ 类 [英] Wrapping a C++ class in Python using SWIG

查看:60
本文介绍了使用 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

example.cpp:

#include "example.h"

int Math::pi() const {
    return this->_pi;
}  
void Math::pi(int pi) {
    this->_pi = pi;
}

example.swig:

%module example
%{ 
    #define SWIG_FILE_WITH_INIT
    #include "example.h"
%}
%include "example.h"

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

I then generate the wrappers, "example.py" and "example_wrap.c" using:

swig  -python example.swig

当我尝试使用以下方法编译包装类时:

When I try to compile the wrapper class using:

g++ -fPIC -c example.cpp example_wrap.c -I/usr/local/include/python2.6/

我收到以下错误:

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"

错误位于以下行:

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

#define SWIG_as_voidptr(a) (void *)((const void *)(a))

生成包装类example_wrap.c"是否正确?

Is it the right way to generate the wrapper class "example_wrap.c"?

推荐答案

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

I think the swig command should be "swig -c++ -python example.swig"

这篇关于使用 SWIG 在 Python 中包装 C++ 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆