Return 来自 C 扩展的 C 字符串数组

Return a C String Array from a C Extension

我有一个 C 函数,它 return 是一个字符串数组。我如何以 Python C 扩展的形式调用它,它将 return 数组返回到调用 Python 函数? (我是 Python C 扩展的新手,对扩展的经验很少)

这是我试过的定义:

static PyObject* _get_array(PyObject* self, PyObject* args)
{
    int64_t value;
    int init_level;
    int final_level;

    if(!PyArg_ParseTuple(args, "Lii", &value, &init_level, &final_level))
        return NULL;

    // returning the array as a Python object by o
    return Py_BuildValue("o", _get_array(value, init_level, final_level));
}

和方法 def:

static PyMethodDef array_methods[] = {
    { "get_array", _get_array, METH_VARARGS, "Returns a string array"},
    { NULL, NULL, 0, NULL }
};

更新

get_array函数:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <Python.h>

char **get_array(int64_t value, int init_level, int final_level) {

  int SHIFTS []= {44, 40, 36, 32, 28, 24, 20, 16, 12, 8, 4, 0};

  long count =  1 << (4* (final_level - init_level));
  char** t_array;
  t_array = malloc(sizeof(char*)*count);

  int shift_coff = 11 -(final_level-init_level);
  int64_t base = (value << SHIFTS[shift_coff]);

  for (long i=0; i < count; i++){
    t_array[i] = malloc((4+final_level)*sizeof(char));
    sprintf(t_array[i], "%llX", (base + i));
  }

  return t_array;
}

您不能 return 您的 char** 直接 Python 因为 Python 只理解 PyObject* 类型的对象(因为它包含处理引用计数和识别类型)。因此,您必须创建一个合适的 Python 对象。最简单的选择是字符串列表。下一个最简单的方法是使用字符串类型的 numpy 数组(您可以轻松做到这一点,因为所有字符串的长度都相同)。这些都没有直接的 Py_BuildValue 转换,因此您必须自己编写循环。


对于字符串列表,您只需使用 PyList_New 创建列表,然后使用 PyList_SetItem:

逐个元素遍历
char** array = get_array(value, init_level, final_level);
PyObject* list = PyList_New(1 << (4* (final_level - init_level)));
if (!list) return NULL;

for (int i=0; i<(1 << (4* (final_level - init_level))); ++i) {
    PyObject* item = PyBytes_FromStringAndSize(array[i],(4+final_level));
    if (!item) goto failed;

    if (PyList_SetItem(list,i,item) != 0) {
        Py_DECREF(item);
        goto failed;
    }

    free(array[i]); // deallocate array as we go
}
free(array);

// returning the array as a Python object by o
return list;

failed:
Py_DECREF(list);
// also deallocate the rest of array?
return NULL;

请注意,我还没有完成失败的内存管理,所以你会泄漏 array


对于numpy数组你分配一个正确字符串类型的数组,然后将数据复制进去

char** array = get_array(value, init_level, final_level);

// create an "Sx" dtype, where x is a suitable number
PyArray_Descr *desc = PyArray_DescrNewFromType(NPY_STRING);
desc->elsize = (4+final_level);

npy_intp array_length[] = {1 << (4* (final_level - init_level))};
PyObject* nparray = PyArray_SimpleNewFromDescr(1,array_length,desc);
if (!nparray) return NULL; // clean up array too

for (int i=0; i<(1 << (4* (final_level - init_level))); ++i) {
    char* data = PyArray_GETPTR1((PyArrayObject*)nparray,i);

    // copy data
    for (int j=0; j<(4+final_level); ++j) {
        data[j] = array[i][j];
    }

    free(array[i]); // deallocate array as we go
}
free(array);

// returning the array as a Python object by o
return nparray;

同样,并非所有的错误处理都是完美的。为了让这个例子工作,你必须在你的模块初始化函数中调用import_array()


在这两种情况下,您最好不要在 get_array 中分配内存,而是直接写入 Python 对象。