swig c ++ to python通过引用返回unsigned char *

时间:2017-11-06 02:33:28

标签: python c++ swig unsigned-char

我正在使用swig将c ++函数包装成python:

int getBytes(unsigned char *& result, int length)

我从this question学到如何通过引用包装函数返回char *:

%typemap(in,numinputs=0) char*& (char* tmp) %{
    $1 = &tmp;
%}

%typemap(argout) char*& (PyObject* obj) %{
    obj = PyUnicode_FromString(*$1);
    $result = SWIG_Python_AppendOutput($result,obj);
%}

%typemap(freearg) char*& %{
    free(*$1);
%}

我尝试将此应用于unsigned char *但失败并获得SWIG_Python_AppendOutput无法将unsigned char **转换为signed char **的错误。我搜索了python doc并没有找到一个可以将unsigned char **转换为unsigned char **的函数。 有人可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:2)

很久以前,我已经解决了这个问题,以下是我的解决方案:

%typemap(in, numinputs= 0) (unsigned char *&result, int &length) (unsigned char *temp, int len) %{
  $1 = &temp;
  $2 = &len;
%}

%typemap(argout) (unsigned char *&result, int &length)  %{
    PyObject* arg5 = 0;
    arg5 = SWIG_FromCharPtrAndSize((const char *)(*$1), *$2);

    PyObject* temp = NULL;
    temp = $result;
    $result = PyList_New(1);
    PyList_SetItem($result, 0, temp);
    PyList_Append($result, (PyObject*)arg5);//unsigned char *&
    PyList_Append($result, PyInt_FromLong(*$2));

    Py_DECREF(temp);
%}