繁体   English   中英

如何使用 ctypes 将 Python 列表转换为 C 数组?

[英]How do I convert a Python list into a C array by using ctypes?

如果我有以下两组代码,如何将它们粘合在一起?

void
c_function(void *ptr) {
    int i;

    for (i = 0; i < 10; i++) {
        printf("%p", ptr[i]);
    }

    return;
}


def python_routine(y):
    x = []
    for e in y:
        x.append(e)

如何使用 x 中的连续元素列表调用 c_function? 我试图将 x 转换为 c_void_p,但这没有用。

我也尝试使用类似的东西

x = c_void_p * 10 
for e in y:
    x[i] = e

但这会出现语法错误。

C 代码显然需要数组的地址。 我怎样才能做到这一点?

以下代码适用于任意列表:

import ctypes
py_values = [1, 2, 3, 4]
arr = (ctypes.c_int * len(py_values))(*py_values)

这是对已接受答案的解释。

ctypes.c_int * len(pyarr)创建一个长度为 4 的c_int类型的数组(序列)( python3python 2 )。 由于c_int是一个其构造函数采用一个参数的对象, (ctypes.c_int * len(pyarr)(*pyarr)对来自pyarr的每个c_int实例进行一次初始化。 更易于阅读的形式是:

pyarr = [1, 2, 3, 4]
seq = ctypes.c_int * len(pyarr)
arr = seq(*pyarr)

使用type函数查看seqarr之间的区别。

ctypes 教程

>>> IntArray5 = c_int * 5
>>> ia = IntArray5(5, 1, 7, 33, 99)
import ctypes
import typing

def foo(aqs : typing.List[int]) -> ctypes.Array:
    array_type = ctypes.c_int64 * len(aqs)
    ans = array_type(*aqs)
    return ans

for el in foo([1,2,3]):
    print(el)

这将给出:

1
2
3

暂无
暂无

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

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