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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4145775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:27:09  来源:igfitidea点击:

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

pythoncctypes

提问by No One in Particular

If I have the follow 2 sets of code, how do I glue them together?

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

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)

How can I call the c_function with a contiguous list of elements in x? I tried to cast x to a c_void_p, but that didn't work.

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

I also tried to use something like

我也尝试使用类似的东西

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

but this gets a syntax error.

但这会出现语法错误。

The C code clearly wants the address of an array. How do I get this to happen?

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

采纳答案by Gabi Purcaru

The following code works on arbitrary lists:

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

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

回答by Ryan Ginstrom

From the ctypes tutorial:

ctypes 教程

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

回答by akhan

This is an explanation of the accepted answer.

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

ctypes.c_int * len(pyarr)creates an array (sequence) of type c_intof length 4 (python3, python 2). Since c_intis an object whose constructor takes one argument, (ctypes.c_int * len(pyarr)(*pyarr)does a one shot init of each c_intinstance from pyarr. An easier to readform is:

ctypes.c_int * len(pyarr)创建一个c_int长度为 4(python3python 2)类型的数组(序列)。由于c_int是一个对象,其构造函数接受一个参数,因此(ctypes.c_int * len(pyarr)(*pyarr)对每个c_int实例进行一次一次初始化pyarr。一个更容易阅读的表格是:

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

Use typefunction to see the difference between seqand arr.

使用type功能看之间的区别seqarr

回答by J?rg Beyer

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)

this will give:

这将给出:

1
2
3