如何使用SWIG在C ++中使用Python列表分配std :: vector? [英] How to use a Python list to assign a std::vector in C++ using SWIG?

查看:195
本文介绍了如何使用SWIG在C ++中使用Python列表分配std :: vector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

编译后,我进入Python并执行以下操作:

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!

我收到的错误消息是:

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

我知道我可以做到:

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

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

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.

这是示例代码.

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

推荐答案

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

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

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

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

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.

这篇关于如何使用SWIG在C ++中使用Python列表分配std :: vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆