Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a Python list to assign a std::vector in C++ using SWIG?

Tags:

c++

python

swig

I have a simple C++ class that contains a std::vector member and a member function that takes a std::vector as an argument that I am wrapping with SWIG and calling from Python. The example code is below.

After compiling it, I go into Python and do:

import test
t = test.Test()
a = [1, 2, 3]
b = t.times2(a) # works fine
t.data = a # fails!

The error message I get is:

TypeError: in method 'Test_data_set', argument 2 of type 'std::vector< double,std::allocator< double > > *'

I know that I can just do:

t.data = test.VectorDouble([1,2,3])

But I would like to know how to just use a Python list directly in the assignment, or at least understand why it doesn't work.


Here's the example code.

test.i:

%module test

%include "std_vector.i"

namespace std {
    %template(VectorDouble) vector<double>;
};

%{
#include "test.hh"
%}

%include "test.hh"

test.hh:

#include <vector>

class Test {
    public:
        std::vector<double> data;
        std::vector<double> times2(std::vector<double>);
};

test.cc:

#include "test.hh"

std::vector<double>
Test::times2(
    std::vector<double> a)
{
    for(int i = 0; i < a.size(); ++i) {
        a[i] *= 2.0;
    }
    return a;
}

makefile:

_test.so: test.cc test.hh test.i
    swig -python -c++ test.i
    g++ -fpic -shared -o _test.so test.cc test_wrap.cxx -I/opt/local/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -L/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config/ -lpython2.7
like image 279
Daniel Matz Avatar asked Mar 18 '14 21:03

Daniel Matz


1 Answers

Try using the %naturalvar directive on the Test::data member. In your test.i file:

%naturalvar Test::data;
%include "test.hh"

As described in the SWIG documentation on C and C++ members, SWIG will default to accessing nested structs and classes via pointers. The %naturalvar directs the interface to be accessed by value rather than by reference.

like image 121
ets Avatar answered Sep 22 '22 01:09

ets