Lukas Mosser
Lukas Mosser

Reputation: 71

Using SWIG to wrap a C++ class that calls another objects member function

I am using swig to write a wrapper to a c++ class for use with python.

When I try to do from CSMPy import * (CSMPy is my module) I get this message:

ImportError: dlopen(/Users/MUL_mac2/anaconda/lib/python2.7/site-packages/_CSMPy.so, 2): Symbol not found: __ZN4csmp4VSetILm2EE6ResizeERKSt5dequeIiSaIiEERKS2_ImSaImEESA_m
  Referenced from: /Users/MUL_mac2/anaconda/lib/python2.7/site-packages/_CSMPy.so
  Expected in: dynamic lookup

A little bit of background:

I have one interface file that has an include to one header file containing my wrapper class:

This class has an object as a private member.

I then want to pass a number of objects of type std::deque<int> to a member function of this object like so: this->object.Function(int_deque_a,int_deque_b) where object is a member of the class I am wrapping using swig.

When I comment the above line out everything works like a charm. All the containers I am passing are valid datatypes to pass to this objects member function and contain the correct number of entries.

Everything compiles and this occurs only on import of the module.

What am I missing here?

I am using distutils to compile using python setup.py install

setup.py:

CSMPy_module = Extension('_CSMPy',
                                  include_dirs = [Bunch of include directories here],
                                  library_dirs = ['MyLibraryPath'],
                                  libraries = ['MyLibrary'],
                                  sources=['CSMPy_wrap.cxx', 'WrapperClass.cpp'],
                                  )
setup (name = 'CSMPy',
   version = '0.1',
   author = "My name",
   description = """Simple Test""",
   ext_modules = [CSMPy_module],
   py_modules = ["CSMPy"],
   )

MyLibrary is a static library.

Edit 1: I am providing you with a version of the code I can show to everyone

Setup.h

#include <iostream>
#include <vector>
#include <deque>

#include "VSet.h"


class Setup {
public:
  Setup();
  ~Setup();

  void InitializeSetup();

private:

  std::deque<size_t> npes;
  std::deque<size_t> epes;

  std::deque<std::vector<size_t> > eni; //plist
  std::deque<std::vector<csmp::int32> > enb; //pfverts
  std::deque<std::vector<csmp::double64> > ncl; //pelmt
  std::map<size_t, csmp::int32> bnf; //bflags

  std::deque<csmp::int32>   et;
  csmp::VSet<2U> v;
};

Setup.cpp

#include "Setup.h"


Setup::Setup() {

  std::cout<<"Setup initialized."<<std::endl;

}

Setup::~Setup() {

}

void Setup::InitializeSetup() {


  for(size_t i = 0; i < this->eni.size(); i++) {

      this->npes.push_back(this->eni[i].size());
  }

  for(size_t i = 0; i < this->enb.size(); i++) {

    this->epes.push_back(this->enb[i].size());

  }
  this->v.Resize(this->et, npes, epes, this->ncl.size()); //This is the line that does not work
}

CSMPy.i

%module CSMPy

%{
#define SWIG_FILE_WITH_INIT
#include "stdlib.h"
#include <vector>
#include <deque>
#include <map>
#include "VSet.cpp"
#include "Setup.h"
#include "Number_Types.h"
%}

%include "Number_Types.h"

%include "std_map.i"
%include "std_vector.i"
%include "std_deque.i"

// Instantiate templates used by CSMPy
namespace std {
  %template() pair<size_t, csmp::int32>;
  %template() pair<size_t, csmp::double64>;

  %template() pair<size_t, vector<size_t> >;
  %template() pair<size_t, vector<csmp::int32> >;
  %template() pair<size_t, vector<csmp::double64> >;

  %template(Deque_SizeT) deque<size_t>;
  %template(Deque_Int) deque<csmp::int32>;

  %template(Vector_SizeT) vector<size_t>;
  %template(Vector_Int32) vector<csmp::int32>;
  %template(Vector_Double64) vector<csmp::double64>;

  %template(Deque_Double64) deque<csmp::double64>;

  %template(Deque_Vector_Int) deque<vector<csmp::int32> >;
  %template(Deque_Vector_SizeT) deque<vector<size_t> >;
  %template(Deque_Vector_Double64) deque<vector<csmp::double64> >;

  %template(Map_SizeT_Int) map< size_t, csmp::int32>;
  %template(Map_SizeT_Double64) map< size_t, csmp::double64>;

  %template(Map_SizeT_Vector_SizeT) map< size_t, vector<size_t> >;
  %template(Map_SizeT_Vector_Int) map< size_t, vector<csmp::int32> >;
  %template(Map_SizeT_Vector_Double64) map< size_t, vector<csmp::double64> >;
}
%include "Setup.h"

Edit 2:

I did nm -gC myLib.so

I found this echo

__ZN4csmp4VSetILm2EE6ResizeERKNSt3__15dequeIiNS2_9allocatorIiEEEERKNS3_ImNS4_ImEEEESC_m

which on c++ tilt tells me:

csmp::VSet<2ul>::Resize(std::__1::deque<int, std::__1::allocator<int> > const&, std::__1::deque<unsigned long, std::__1::allocator<unsigned long> > const&, std::__1::deque<unsigned long, std::__1::allocator<unsigned long> > const&, unsigned long)

couple of notes on this, I have switched to using clang++ as my compiler and manually compiling. I have also put #include "VSet.cpp" in my .i file. (See edit in previous post)

I am now getting this error on import in python:

Symbol not found: __ZN4csmp5VData6InTextERSt14basic_ifstreamIcSt11char_traitsIcEE
  Referenced from: ./_CSMPy.so
  Expected in: flat namespace

I have also created a main that will instantiate the object and the call to Initialize() works.

Upvotes: 0

Views: 2103

Answers (3)

Oliver
Oliver

Reputation: 29591

I'm starting a new answer because the fact that VSet<2U> is not wrapped makes most of my other answer not relevant to this problem (although everything in there is still correct). And the fact that Setup has a data member of type VSet<2U> is not relevant to SWIG since you aren't accessing Setup::v directly from Python.

Verify that Setup works without Python or SWIG: create a void main() where you instantiate a Setup and call its InitializeSetup() method, build and run. Most likely yo will get same runtime error due to symbol not found.

The Setup object code is looking for

csmp::VSet<2ul>::Resize(
    const std::deque<int>&, 
    const std::deque<unsigned long> &, 
    const std::deque<unsigned long> &,
    unsigned long)

So verify that your DLL has this symbol:

~> nm -gC yourLib.so

It probably doesn't. Are there other Resize overloads that were instantiated? This can give a clue.

There could be a variety of reasons why the compiler failed to instantiate the Resize for VSet<2U>. For example, a template class's method definitions must appear in the .h otherwise how it the compiler going to know what code to generate? If you tell the compiler to compile VSet.cpp it won't generate anything in the .o unless you explicitly instantiate the template for a specific type. Then the .o will contain object code for class of that specific templated class with that type. I like to have my method definitions separate class definition, but then I include the .cpp in the .h since any user of the .h would need to also nclude the .cpp so compiler can generate the right code. For you this would mean you would have at the bottom of VSet.h an #include "VSet.cpp" // templated code.

Upvotes: 0

Oliver
Oliver

Reputation: 29591

It's not finding the symbol

__ZN4csmp4VSetILm2EE6ResizeERKSt5dequeIiSaIiEERKS2_ImSaImEESA_m

in the .so. Thanks to Dave for demangling this, we now know that it refers to

csmp::VSet<2ul>::Resize(
    const std::deque<int>&, 
    const std::deque<unsigned long> &, 
    const std::deque<unsigned long> &)

So it is a little odd that you have two types of deques, based on what you posted.

Here are some things to try:

  1. Verify that your _CSMP.so links to the STL library that comes with your compiler, you may have to specify an extra switch or field in your setup.py. Your code works when Resize is not there, you say, so that's not likely the problem.
  2. turn on verbose output in your setup.py so that you can see the compilation and link command line parameters
  3. make sure you %include std_deque.i in your SWIG .i file. You're not getting compile error so this is not likely the issue.
  4. verify that you have instantiated your deque<int> with a %template(IntDeque) std::deque<int> in your .i, since Python knows nothing about C++ templates, and a template is not a class, but a recipe so compiler can create a class for you. If you really do use both int and unsigned long, you have to instantiate both. I'm only seeing int and size_t in your code. You can't assume that size_t is same as unsigned long.
  5. Confirm that your DLL contains an intantiation of this Resize method for unsigned int. in your C++ code. I think you defined the size_t version via, or are the unsigned long unexpected?

About #5:

SWIG generates a header and a source file. In the header it puts functions that adhere to the Python C API and registers them in the Python interpreter, and in the body of those functions it figures out what C/C++ functions to call from your library. The fact that the above Resize is not found in DLL is an indication that SWIG thinks this overload of Resize is needed, so it is called from the function it generated, but your C++ lib did not instantiate it.

How is this possible? In your C++ lib, you have a class template with a Resize method. The trick with class templates is that the compiler will only generate code for the methods that are used in the DLL (so if your class defines 5 methods but your DLL only uses 1, it won't generate code for the other 4 methods), except if you explicitly instantiate the template in your library. You would do this by putting a statement

template class VSet<2ul>; 

(whatever 2ul stands for) either in your C++ DLL, or the wrapper DLL via the %template directive in your .i file. This will instantiate all methods of VSet<2ul>, so Resize will be there too. IF the Resize thus generated has parameters deque<int> and deque<unsigned long>. Your code indicates that you are assuming that size_t is unsigned int. If size_t is typedefd to unsigned int, SWIG should be able to handle it, but maybe there is a bug. Better not assume. You could add a Resize overload for unsigned int. Or you could create an inline extension method in Setup taking two unsigneld long deques and calling the size_t version. Something like

%template DequeULong std::deque<unsigned long>

%extend Setup {
   void Resize(const DequeInt& a, const DequeULong& b) 
   {
       DequeSizet c;
       ... copy b into a DequeSizet
       Resize(a, c);
   }
}

Upvotes: 3

David Hammen
David Hammen

Reputation: 33126

The problem most likely isn't a compilation issue. It's much more likely that there's a mismatch between your header file and implementation files. The header promises an interface that you aren't implementing. You won't see the undefined reference in a standalone, C++-only application if you never call that member function in your C++ code.

The mismatch between header and implementation becomes a real problem when you tell SWIG to wrap that C++ header. The generated SWIG code contains a reference to that unimplemented function. The dynamic linking fails because that function is never defined.

So what function is it? Look at the error message:

Symbol not found: __ZN4csmp4VSetILm2EE6ResizeERKSt5dequeIiSaIiEERKS2_ImSaImEESA_m

This tells you exactly what's missing, but in a very convoluted (name mangled) way. Copy that symbol, open a terminal window, and issue the command echo <paste mangled name here> | c++filt:

echo __ZN4csmp4VSetILm2EE6ResizeERKSt5dequeIiSaIiEERKS2_ImSaImEESA_m | c++filt

The c++filt utility is a very useful capability on Macs and Linux boxes. In this case it gives you the unmangled name of the missing symbol. See my comment to Schollii's answer.

Upvotes: 1

Related Questions