简体   繁体   English

Python C Extension通过引用传递参数

[英]Python C Extension passing arguments by reference

I am trying to write a python C wrapper for a function (libFunc) whose prototype is 我正在尝试为函数(libFunc)编写一个python C包装器,其原型是

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

How do I use PyArg_ParseTuple for setting up the arguments for function call. 如何使用PyArg_ParseTuple设置函数调用的参数。 Here is what I currently have 这是我现在拥有的

#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);
    }

I am able to do the same with ctypes using byref. 我可以使用byref对ctypes做同样的事情。

I ended up doing it this way 我最终这样做了

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM