Python的C扩展引用传递

问题描述:

论点我想写一个python C包装的功能(libFunc),其原型是Python的C扩展引用传递

libFunc(char**, int*, char*, int) 

如何使用PyArg_ParseTuple为函数调用设置的参数。这是我目前有的

#include <Python.h> 

    PyObject* libFunc_py(PyObject* self, PyObject* args) 
    { 
     char* input; 
     char** output; 
     int inputlen; 
     int* outputlen; 

     PyArg_ParseTuple(args, "sisi" , output, outputlen, &input, &inputlen); 


     int ret = libFunc(output, outlen, input, inputlen); 


     return Py_BuildValue("i", ret); 
    } 

我能够使用byref做ctypes。

+1

这是一个使用的例子[用Cython(http://cython.org):libfunc.pyx](https://gist.github.com/cf5e036a88d1b12ea64a) – jfs

+0

感谢代码..但我没有在我的环境pyrex。你能告诉我,如何在下面的代码中释放内存(由libfunc分配)? – Kamal

+1

1.您的代码的用户不需要Cython。您只需要它为您生成C源代码。 2.如果'libFunc()'使用'malloc()'为'output'分配内存,则可以调用'free(输出)'。 3. s/outlen/outputlen/ – jfs

最后我做这种方式

#include <Python.h> 

    PyObject* libFunc_py(PyObject* self, PyObject* args) 
    { 
     char* input; 
     char* output; 
     int inputlen; 
     int outputlen; 

     PyArg_ParseTuple(args, "s#" , &input, &inputlen); 


     int ret = libFunc(&output, &outlen, input, inputlen); 

     if (ret !=0) 
     { 
      Py_ErrSetString(PyExc_RunTimeError, "ErrorMessage"); 
      return NULL; 
     } 

     PyObject* retStr = Py_BuildValue("s#", output,outputlen); 

     if(output) 
      free(output) 

     return retStr; 
    } 
+2

1.'if(!PyArg_ParseTuple(...))return NULL;'2.您可以使用['{PyErr_SetString(PyExc_RuntimeError,“Error message”);返回NULL; }'](http://www.google.com/codesearch#search/&q=PyErr_SetString\%28PyExc_RuntimeError&type=cs),而不是'返回Py_BuildValue(“s#”,“Error”,5)'。 – jfs