C ++ - 带SWIG的类

时间:2011-10-14 15:48:41

标签: c++ python swig

我尝试用C ++创建一个python接口(带swig) - 代码。使用下面的代码。当我删除该行时:

aClass z = aClass(1);
从.cpp文件

我收到以下错误:

Traceback (most recent call last):
  File "./testit.py", line 3, in <module>
    import testlib
  File "(...)/testlib.py", line 26, in <module>
_testlib = swig_import_helper()
 File "(...)/testlib.py", line 22, in swig_import_helper
_mod = imp.load_module('_testlib', fp, pathname, description)
ImportError: (...)/_testlib.so: undefined symbol: _ZN6aClassC1Ei

我做错了什么?

testlib.cpp

#include <iostream>
#include <string.h>
using namespace std;

class aClass {
    public:
        aClass(int i) {
            iD = i;
        }
        void printiD() {
            cout << iD << endl;
        }
    private:
        int iD;
};

void doSomething(string s) {
    cout << "testlib: I did something with:" << s << endl;
}

void outprintiD(aClass ff) {
    ff.printiD();
}
string returnSomething(string s) {
    return s;
}
//Don't know why, but without the next line it doesn't work. :(
aClass z = aClass(1);

testlib.i

%module testlib
%include "std_string.i"
using namespace std;
%{
    class aClass {
public:
    aClass(int i);
    void printiD();
private:
    int iD;
};
void outprintiD(aClass ff);
void doSomething(std::string s);
std::string returnSomething(std::string s);
%}
class aClass {
public:
    aClass(int i) ;
    void printiD();
private:
    int iD;
};
void outprintiD(aClass ff);
void doSomething(std::string s);
std::string returnSomething(std::string s);

testit.py

#!/usr/bin/python
import testlib

testlib.doSomething("doS");
var = testlib.returnSomething("rSo");
print var

aClassInstance = testlib.aClass(42)
testlib.outprintiD(aClassInstance)

print "done..."

执行脚本

swig -c++ -python $1.i
g++ -c -fPIC $1.cpp $1_wrap.cxx -I/usr/include/python2.7
g++ -shared $1.o $1_wrap.o -o _$1.so

1 个答案:

答案 0 :(得分:0)

vines@Aspire-5755G:~$ c++filt _ZN6aClassC1Ei
aClass::aClass(int)

这是一个链接器错误。尝试:

g++ -shared $1_wrap.o $1.o -o _$1.so

即。交换目标文件。这是因为它们的顺序很重要,并且假设$1_wrap.o想要从$1.o中提取某些方法是合理的。