【发布时间】: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
【问题讨论】: