gpt4 book ai didi

python - 填充python ctypes指针

转载 作者:行者123 更新时间:2023-11-30 23:43:28 25 4
gpt4 key购买 nike

我有一个 C 函数 uint8_t *begin();,它返回指向已分配内存的指针。

这是一个与之绑定(bind)的ctypes:

begin = mylibrary.begin
begin.argtypes = ()
begin.restype = ctypes.POINTER(ctypes.c_uint8)

我需要用整数数组填充内存。有没有比这个更快的方法?

buffer = begin()
data = range(10)
for idx, value in enumerate(data):
buffer[idx] = ctypes.c_uint8(value)

在我看来,迭代整个数组并不是一种非常快的方法,因为可迭代数据可以包含很多项、数百万个整数或类似的东西。

最佳答案

如果可以添加依赖项,numpy让这变得更容易。

这是我整理的一个示例。

C(注意长度设置为10)

#include <stdlib.h>
int *begin(void) {
return calloc(10, sizeof(int));
}

和 python

import numpy as np
import ctypes
# make the data I want to put into C
data = np.arange(10, dtype=ctypes.c_int)
# setup the ctypes just as you did
mylibrary = ctypes.CDLL('a.out')
begin = mylibrary.begin
begin.argtypes = ()
begin.restype = ctypes.POINTER(ctypes.c_int)
# and do the same memmove that Kirill suggested
ctypes.memmove(buffer, data.ctypes.get_data(), ctypes.sizeof(ctypes.c_int)*len(data))
# and print some out
print buffer[2]
# 2

如果你擅长使用 numpy,你也可以用这种方式处理多维数组。

当您接近底层 C 时,需要考虑一下谁拥有内存以及如何清除它,而不是在任何地方出现段错误(或泄漏)。例如 del buffer 将不释放创建的缓冲区,这必须在 C 中完成。

关于python - 填充python ctypes指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10730841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com