2014-09-25 3 views
0

비표준 벡터 대신에 파이썬리스트를 전달할 수 있도록 typemap을 설정하고 싶습니다.swig, 목록에서 비표준 벡터

C++에서 나는

template<typename T> 
class mm_vector 
{ 
void set_mm_vector(const mm_vector * copy); 
} 

내가 인수로 파이썬 목록을 통과 할 수 있도록하려면, 그래서 내 .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 
    } 
} 

을 그리고 이 라인

l=[0,1] 
v = mm.vec_of_ints() 
v.set_mm_vector(l) 

나는 다음과 같은 오류가

:

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 

나는 어떤 제안에도 감사 할 것입니다!

답변

2

SWIG는 벡터와 템플릿을 기본적으로 지원하므로 처음부터 구현할 필요가 없습니다.

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

출력 :

>>> import vec 
>>> t=vec.Test() 
>>> t.set([1,2,3]) 
>>> t.get() 
(1, 2, 3) 
다음은 간단한 예제