开发者

C++-classes with SWIG

开发者 https://www.devze.com 2023-04-12 21:23 出处:网络
I try to create a python interface (with swig) from C++-code. With the code below. When I remove the line:

I try to create a python interface (with swig) from C++-code. With the code below. When I remove the line:

aClass z = aClass(1);

from the .cpp-file i get the following error:

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

What am I doing wrong?

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开发者_JAVA百科::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..."

execution script

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


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

It's a linker error. Try:

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

i.e. swap the object files. It's because the order they are given matters, and it's reasonable to suppose that $1_wrap.o wants to pull some methods from $1.o.

0

精彩评论

暂无评论...
验证码 换一张
取 消