简体   繁体   中英

using SWIG with C++

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM