开发者

using SWIG with C++

开发者 https://www.devze.com 2023-01-09 16:39 出处:网络
HI all开发者_高级运维 I am trying to use SWIG to export C++ code to Python. The C sample I read on the web site does work but I have problem with C++ code.

HI all

开发者_高级运维

I am trying to use SWIG to export C++ code to Python. The C sample I read on the web site does work but I have problem with C++ code.

Here are the lines I call

swig -c++ -python SWIG_TEST.i
g++ -c -fPIC SWIG_TEST.cpp SWIG_TEST_wrap.cxx -I/usr/include/python2.4/
gcc --shared SWIG_TEST.o SWIG_TEST_wrap.o -o _SWIG_TEST.so -lstdc++

When I am finished I receive the following error message

ImportError: ./_SWIG_TEST.so: undefined symbol: Py_InitModule4

Do you know what it is?


It looks like you aren't linking to the Python runtime library. Something like adding -lpython24 to your gcc line. (I don't have a Linux system handy at the moment).


you might try building the shared library using gcc

g++ -shared SWIG_TEST.o SWIG_TEST_wrap.o -o _SWIG_TEST.so

rather than using ld directly.


As Mark said, it's a problem linking to the python library. A nice way to get hints as to just which flags you need to successfully link can be gotten by running python-config --ldflags. In fact, a particularly painless way of compiling your test is the following:

swig -c++ -python SWIG_TEST.i
g++ -c `python-config --cflags` -fPIC SWIG_TEST.cpp SWIG_TEST_wrap.cxx
gcc --shared `python-config --ldflags` SWIG_TEST.o SWIG_TEST_wrap.o -o _SWIG_TEST.so -lstdc++

Note that python-config isn't perfect; it sometimes gives you extra things, or conflicting things. But this should certainly help a lot.

0

精彩评论

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