SWIG with C ++ patterns: undefined character

C ++ Templates and SWIG do not play well for me.

When I try to import my module, I get an error

ImportError: ./_simple.so: undefined symbol: _Z9double_itIiET_S0_ 

I am using SWIG 1.3.

Here is a simple example showing the problem:

 //file: simple.h template <typename T> T double_it (T a); //file: simple.cc template <typename T> T double_it (T a) { return (2 * a); } //file: simple.i %module "simple" %{ #include "simple.h" %} %include "simple.h" %template(int_double_it) double_it <int>; %template(float_double_it) double_it <float>; #file: setup.py from distutils.core import setup, Extension simple_module = Extension('_simple', sources=['simple.i', 'simple.cc'], swig_opts=['-c++'], ) setup (name = 'simple', ext_modules = [simple_module], py_modules = ["simple"], ) 

Then create using:

 python setup.py build 

If I include the contents of simple.cc in simple.i and delete the link to simple.cc from setup.py, then everything works fine, but this is not a solution when the situation becomes more complicated.

Iโ€™ll give a counter example of what seems to be, but doesnโ€™t use templates and works fine.

 //file: simple.h int double_it (int a); //file: simple.cc int double_it (int a) { return (2 * a); } //file: simple.i //Same as before but with %template statements removed. %module "simple" %{ #include "simple.h" %} %include "simple.h" #file: setup.py #Identical to previous example. 
+4
source share
1 answer

Typically, templates are defined in the header file, not in the cc file. With the setting you have, the compiler cannot find / compile the template implementation.

You will need to change the organization of the code so that the implementation of the template is available:

 //file: simple.hh template <typename T> T double_it (T a) { return (2 * a); } //file: simple.i %module "simple" %{ #include "simple.hh" %} %include "simple.hh" // include it directly into here %template(int_double_it) double_it <int>; %template(float_double_it) double_it <float>; #file: setup.py from distutils.core import setup, Extension simple_module = Extension('_simple', sources=['simple.i', 'simple.hh'], swig_opts=['-c++'], ) setup (name = 'simple', ext_modules = [simple_module], py_modules = ["simple"], ) 

I appreciate that your example is simplified, but it illustrates the point. You do not need to directly execute the %include implementation (but you need #include it), but you need to provide some implementation to the SWIG compiler, even if it is a simplified version.

The above should help you.

+3
source

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


All Articles