0

so for my job I am using swig to pass an array through SWIG from a python file to a c++ file. I can get it to work, but not if it is inside a class. I am new to SWIG and I found the implementation here. If the array function is inside of my class I am getting this error. I want the function to be inside of the class because there are other functions I need to use to alter the array. The following code is a simplistic version of what I am trying to do, but the error is still the same and same issue applies. I would appreciate any guidance and help.

Traceback (most recent call last):
File "/root/Documents/SWIG_VECTOR/filter.py", line 1, in <module>
  import test
File "/root/Documents/SWIG_VECTOR/test.py", line 15, in <module>
  import _test
ImportError: /root/Documents/SWIG_VECTOR/_test.so: undefined symbol: 
_ZN7myClass11print_arrayESt6vectorIdSaIdEE

test.i

%module test
%{
#include "test.hpp"
%}

%include "std_vector.i"

%template(Array) std::vector < double >;

class myClass {
public:
    void print_array(const std::vector < double > myarray);
}; 

test.hpp

#ifndef TEST_HPP__
#define TEST_HPP__

#include <iostream>
#include <stdio.h>
#include <vector>

//#include "mySecondClass.hpp"

class myClass {
public:
    void print_array(std::vector < double > myarray);
};


#endif /* TEST_HPP__ */

test.cpp

#include "test.hpp"

void print_array(std::vector < double >  myarray)
{
  for (int i =0; i < myarray.size(); ++i) {
    std::cout << myarray.size() << " ";
  }
}

I use these swig commands to compile.

swig -python -c++ -Isrc test.i
g++ -Isrc -fPIC -c $(pkg-config --cflags --libs python3) test.cpp test_wrap.cxx
g++ -shared -o _test.so test.o test_wrap.o
  • The error is saying that you never defined `myClass::print_array()`. The code you posted supports that, as there is no definition of that member function. Disagree? Please point to the definition and look for that double colon. – JaMiT Nov 25 '21 at 01:47
  • I don't see a duplicate of this specific issue (but there probably is one). So I'll just defer to the generic __What is an undefined reference/unresolved external symbol error and how do I fix it?__ question, in particular the _"A common mistake is forgetting to qualify the name"_ section of the [Common issues with class-type members](https://stackoverflow.com/a/12574407) answer. – JaMiT Nov 25 '21 at 01:57

1 Answers1

0

Change test.cpp to:

#include "test.hpp"

void myClass::print_array(std::vector < double >  myarray)
//   ^^^^^^^^^
{
  for (int i =0; i < myarray.size(); ++i) {
    std::cout << myarray.at(i) << " ";
    //                  ^^^^^^
  }
}
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251