C ++ wrapper for python using SWIG. Cannot use cout command

I am trying to wrap this simple C ++ code for python using SWIG:

#include "hello.h" int helloW() { std::cout << "Hello, World!" ; return 0; } 

and here is the relative heading:

 #include <iostream> int helloW() ; // decl 

As input SWIG file I use:

 /* file : pyhello.i */ /* name of module to use*/ %module pyhello %{ #include "hello.h" %} %include "hello.h"; 

Now my makefile (which works fine):

 all: swig -c++ -python -Wall pyhello.i gcc -c -fpic pyhello_wrap.cxx hello.cpp -I/usr/include/python2.7 gcc -shared hello.o pyhello_wrap.o -o _pyhello.so 

because I managed to collect information from various sources about the problem on the Internet. Now, as soon as I try to import my library into python, as is done with the command

 >>> import pyhello 

This is the error I get:

  Traceback (most recent call last): File "<stdin>", line 1, in <module> File "pyhello.py", line 17, in <module> _pyhello = swig_import_helper() File "pyhello.py", line 16, in swig_import_helper return importlib.import_module('_pyhello') File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: ./_pyhello.so: undefined symbol: _ZSt4cout 

What makes me such a problem is something about the std::cout command or, in general, the <iostream> standard library.

Hope someone can give me some advice on this issue. Thank you very much in advance!

NOTE : same issue. I am trying to use printf() instead of std::cout and the <cstdio> library instead of <iostream>

+5
source share
1 answer

ImportError: ./_ pyhello.so: undefined symbol: _ZSt4cout

with c++filt _ZSt4cout you will know that it is std::cout ( name mangling ).

You should use g++ , not gcc , especially on your linker command (with -shared ).

Or you need to explicitly specify a link with some -lstdc++ your shared library.

Reading Drepper How to write shared libraries (since Python is dlopen (3) , then dlsym (3) is it).

It is better to declare as extern "C" int helloW(void); your routine (read C ++ dlopen minihowto ).

+3
source

Source: https://habr.com/ru/post/1274715/


All Articles