填充python ctypes指针 [英] Fill python ctypes pointer

查看:126
本文介绍了填充python ctypes指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a C function uint8_t *begin(); which returns a pointer to allocated memory.

这是绑定到它的 ctypes

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

我需要用整数数组填充内存。

I need to fill memory with an array of the integers. Is there any quicker way to do it instead of this?

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

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

It doesn't look to me, that iterating over the whole array is a very fast method, because that iterable data can contains a lot of items, millions of integers or something like this.

推荐答案

如果可以添加依赖项,请 numpy 使此操作变得更容易。

If you can add dependencies, numpy makes this easier.

这里是我放在一起的一个示例。

Here is an example I put together.

C(注意长度设置为10)

The C (note the length is set to 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很聪明,也可以采用这种方式来处理多维数组。

If you are clever with numpy you can do multidimensional arrays this way too.

一个人需要思考一下关于谁拥有内存以及如何清除内存,而不是在接近底层C时在任何地方进行段错误(或泄漏)。例如, del缓冲区不会释放内存。创建的缓冲区,必须在C中完成。

One needs to think a bit on who owns the memory and how to clear it out and not segfault (or leak) anywhere as you are getting close the the underlying C. For example del buffer will not free the created buffer, that has to be done in C.

这篇关于填充python ctypes指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆