Skip to content

Instantly share code, notes, and snippets.

@tsbertalan
Last active December 10, 2015 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsbertalan/4349180 to your computer and use it in GitHub Desktop.
Save tsbertalan/4349180 to your computer and use it in GitHub Desktop.
How to return a double * from swig as a Python list? Use a std::vector instead.
returnList.py
_returnList.so
*_wrap.cxx
#include "returnList.h"
#include <iostream>
int main(){
FooGiver *fg = new FooGiver();
// for( std::vector<double>::const_iterator i = fg->wGiver().begin(); i != fg->wGiver().end(); ++i){
// std::cout << *i << ' ';
// }
// std::cout << std::endl;
delete fg;
return 0;
}
CXXFLAGS = -g -Wall -std=c++0x # -pedantic
PYTHON_INCLUDE_DIR = "/usr/include/python2.6"
all: swig-return
clean:
$(RM) *.o
$(RM) .depend
$(RM) *_wrap.cxx
$(RM) *.so
$(RM) *.pyc
$(RM) returnList.py
swig-return:
swig -python -c++ returnList.swg
$(CXX) -fPIC -shared -o _returnList.so returnList.cc returnList_wrap.cxx -I$(PYTHON_INCLUDE_DIR)
python returnList_demo.py
cpp-only:
g++ -g returnList.cc cppUser.cc -o cppUser && ./cppUser
#include "returnList.h"
FooGiver::FooGiver(){
toReturn = std::vector<double>(4);
for(int i=0; i<toReturn.size(); i++){
toReturn[i] = i * 2;
}
}
FooGiver::~FooGiver(){
// delete toReturn;
;
}
std::vector<double> FooGiver::foo(){
return toReturn;
}
#include <vector>
class FooGiver {
public:
FooGiver();
~FooGiver();
std::vector<double> foo();
private:
std::vector<double> toReturn;
};
%module returnList
%include "std_vector.i"
namespace std {
%template(IntVector) vector<int>;
%template(DoubleVector) vector<double>;
}
%include "returnList.h"
%{
#include "returnList.h"
%}
import returnList
giver = returnList.FooGiver()
foo = giver.foo()
print foo
print [v for v in foo]
print type(foo)
print list(foo)
print type(list(foo))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment