Reputation: 333
I'm trying to wrap a C++ which creates a 3D vector so I can call it from Python and visualise the data. I'm trying to wrap with SWIG but when I do I get the error message
'vector’ was not declared in this scope
and having included "vector" into every file I can think of I'm not sure what I have to do to include it. I've created a set of very basic test functions to try to see where the problem is, it's roughly similar to the real code I'm trying to run.
test.cpp
#include <vector>
#include <iostream>
using namespace std;
vector<int> testfunction(vector <int>& value){
cout <<"Running\n";
return value;
}
test.h
#ifndef TEST_H_ // To make sure you don't declare the function more than once by including the header multiple times.
#define TEST_H_
#include <vector>
#include <iostream>
vector<int> testfunction(vector <int>& value);
test.i
/*test.i*/
%module test
%{
#include "test.h"
#include <vector>
%}
vector<double> testfunction(vector<double> value);
To compile I'm using the following
g++ -g -ggdb -c -std=c++0x -I /include/python2.7 -o run test.cpp
swig -c++ -python test.i
gcc -fpic -c test.cpp test_wrap.cxx -I /include/python2.7
gcc -shared test.o test_wrap.o -i _test.so
Can anyone tell me where I'm going wrong?
Upvotes: 4
Views: 1487
Reputation: 333
I've found the answer to this problem and I'll post the updated code here. The problem was two fold:
The following should compile and run.
example.h
#ifndef TEST_H_
#define TEST_H_
#include <vector>
#include <iostream>
std::vector<int> testfunction(std::vector <int>& value);
#endif
example.cpp
#include <vector>
#include <iostream>
std::vector<int> testfunction(std::vector <int>& value){
std::cout <<"Running\n";
return value;
}
example.i
%module example
%{
#include "example.h"
%}
%include "std_vector.i"
// Instantiate templates used by example
namespace std {
%template(IntVector) vector<int>;
%template(DoubleVector) vector<double>;
}
// Include the header file with above prototypes
%include "example.h"
makefile
all:
g++ -g -ggdb -std=c++0x -I include/python2.7 -o run example.cpp example_run.cpp
swig -c++ -python example.i
gcc -fpic -c example.cpp example_wrap.cxx -I include/python2.7
gcc -Wl,--gc-sections -fPIC -shared -lstdc++ example.o example_wrap.o -o _example.so
Python call:
>>> import example as ex
>>> iv=ex.IntVector(1)
>>> ex.testfunction(iv)
Happy Vectoring!
Upvotes: 3