[英]swig, from list to non-standard vector
I want to set up typemap, so that instead of non-standard vector we can pass a Python list. 我想设置typemap,以便我们可以传递Python列表而不是非标准矢量。
In C++ I have 在C ++中
template<typename T>
class mm_vector
{
void set_mm_vector(const mm_vector * copy);
}
I want to be able to pass Python list as an argument, so I specify in my .i file: 我希望能够将Python列表作为参数传递,因此我在.i文件中指定:
// python list into vec_of_ints: from Python to C++
%typemap(in) AMM::mm_vector<int>*
{
int i;
if (!PyList_Check($input))
{
PyErr_SetString(PyExc_ValueError, "Expecting a list");
return NULL;
}
Py_ssize_t size = PyList_Size($input); //get size of the list
for (i = 0; i < size; i++)
{
PyObject *s = PyList_GetItem($input,i);
if (!PyInt_Check(s))
{
PyErr_SetString(PyExc_ValueError, "List items must be integers");
return NULL;
}
$1->push_back((int)PyInt_AS_LONG(s)); //put the value into the array
}
}
And when I try to run these lines 当我尝试运行这些行时
l=[0,1]
v = mm.vec_of_ints()
v.set_mm_vector(l)
I have the following error: 我有以下错误:
File "...", line 1295, in set_mm_vector
def set_mm_vector(self, *args): return _pyamt.vec_of_ints_set_mm_vector(self, *args)
ValueError: Expecting a list
I will be grateful for any suggestion !!! 我将不胜感激任何建议!
SWIG has built-in support for vectors and templates so you don't have to implement it from scratch. SWIG具有对矢量和模板的内置支持,因此您不必从头开始实现它。 Here's a short example: 这是一个简短的示例:
%module vec
// Include the built-in support for std::vector
%include <std_vector.i>
// Tell SWIG about the templates you will use.
%template() std::vector<int>;
// %inline adds the following code to the wrapper and exposes its interface via SWIG.
%inline %{
class Test {
std::vector<int> m_v;
public:
void set(const std::vector<int>& v) { m_v = v;}
std::vector<int> get() const {return m_v;}
};
%}
Output: 输出:
>>> import vec
>>> t=vec.Test()
>>> t.set([1,2,3])
>>> t.get()
(1, 2, 3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.