如何使用Python列表使用SWIG在C ++中分配std :: vector?

时间:2014-03-18 22:00:00

标签: python c++ swig

我有一个简单的C ++类,它包含一个std :: vector成员和一个成员函数,它将std :: vector作为一个参数,我用SWIG包装并从Python调用。示例代码如下。

编译之后,我进入Python并执行:

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

我得到的错误信息是:

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

我知道我可以这样做:

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

但我想知道如何直接在作业中使用Python列表,或者至少理解它为什么不起作用。


这是示例代码。

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;
}

生成文件:

_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

2 个答案:

答案 0 :(得分:4)

尝试在%naturalvar成员上使用Test::data指令。在test.i文件中:

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

CC++成员的SWIG文档所述, SWIG将默认通过指针访问嵌套的结构和类。 %naturalvar指示通过值而不是引用访问接口。

答案 1 :(得分:0)

查看SWIG文档中的typemaps示例章节: http://www.swig.org/Doc2.0/SWIGDocumentation.html#Typemaps_nn40(在示例结尾处讨论结构访问)。

您可能需要为数据成员添加memberin类型地图,如果SWIG out尚未提供这些类型地图,则可能instd_vector.i