【问题标题】:How to use a Python list to assign a std::vector in C++ using SWIG?如何使用 Python 列表在 C++ 中使用 SWIG 分配 std::vector?
【发布时间】:2014-03-18 21:59:59
【问题描述】:

我有一个简单的 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

【问题讨论】:

    标签: python c++ swig


    【解决方案1】:

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

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

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

    【讨论】:

    • 但是,现在我无法更改数据的元素。如果我这样做t = test.Test(); t.data = [1, 2, 3]; t.data[0] = 4,它会在最后一行失败并显示“'tuple' 对象不支持项目分配”。
    【解决方案2】:

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

    您可能需要为您的数据成员添加一个 memberin 类型映射,如果 SWIG 尚未提供 std_vector.i,可能还需要添加 outin

    【讨论】:

    • memberin 类型映射适用于已转换的输入。该错误似乎在此之前发生。 times2 的包装器调用 swig::asptr,它可以工作,而用于设置数据变量的包装器调用 SWIG_ConvertPtr,它会失败。所以也许你在正确的轨道上,但我需要找到合适的类型图来修复......
    猜你喜欢
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    相关资源
    最近更新 更多