【问题标题】:Python tuple to C arrayPython元组到C数组
【发布时间】:2014-08-28 15:13:24
【问题描述】:

我正在编写一个 C 函数,它将 Python tupleints 作为参数。

static PyObject* lcs(PyObject* self, PyObject *args) {
    int *data;
    if (!PyArg_ParseTuple(args, "(iii)", &data)) {
        ....
    }
}

我可以转换一个固定长度的元组(这里是 3 个),但是如何从任意长度的 tuple 中得到一个 C array

import lcs
lcs.lcs((1,2,3,4,5,6)) #<- C should receive it as {1,2,3,4,5,6}

编辑

我可以传递一个由“;”分隔的带有数字的字符串,而不是一个元组。例如 '1;2;3;4;5;6' 并将它们分隔到 C 代码中的数组中。但我不认为这是一种正确的做法。

static PyObject* lcs(PyObject* self, PyObject *args) {
    char *data;
    if (!PyArg_ParseTuple(args, "s", &data)) {
        ....
    }
    int *idata;
    //get ints from data(string) and place them in idata(array of ints)
}

编辑(解决方案)

我想我找到了解决办法:

static PyObject* lcs(PyObject* self, PyObject *args) {
    PyObject *py_tuple;
    int len;
    int *c_array;
    if (!PyArg_ParseTuple(args, "O", &py_tuple)) {
      return NULL;
    }
    len = PyTuple_Size(py_tuple);
    c_array= malloc(len*4);
    while (len--) {
        c_array[len] = (int) PyInt_AsLong(PyTuple_GetItem(py_tuple, len));
   //c_array is our array of ints :)
    }

【问题讨论】:

    标签: python c arrays tuples


    【解决方案1】:

    使用 PyArg_VaParse:https://docs.python.org/2/c-api/arg.html#PyArg_VaParse 它适用于 va_list,您可以在其中检索可变数量的参数。

    更多信息在这里:http://www.cplusplus.com/reference/cstdarg/va_list/

    由于它是一个元组,您可以使用元组函数:https://docs.python.org/2/c-api/tuple.html,例如 PyTuple_Size 和 PyTuple_GetItem

    这里有一个如何使用它的例子:Python extension module with variable number of arguments

    如果对你有帮助,请告诉我。

    【讨论】:

    【解决方案2】:

    不确定这是否是您要查找的内容,但是 您可以使用 va_list 和 va_start 编写一个接受可变数量参数的 C 函数。 教程在这里:http://www.cprogramming.com/tutorial/c/lesson17.html

    【讨论】:

    • 来自手册:“C 函数总是有两个参数,通常命名为 self 和 args。”
    猜你喜欢
    • 2014-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多