有效地将字符串(或元组)转换为ctypes数组 [英] efficiently convert string (or tuple) to ctypes array

查看:111
本文介绍了有效地将字符串(或元组)转换为ctypes数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有获取PIL图像并将其转换为ctypes数组以传递给C函数的代码:

I've got code that takes a PIL image and converts it to a ctypes array to pass out to a C function:

w_px, h_px = img.size
pixels = struct.unpack('%dI'%(w_px*h_px), img.convert('RGBA').tostring())
pixels_array = (ctypes.c_int * len(pixels))(*pixels)

但是我要处理的是大图,将很多项目分解成函数参数似乎很慢.要获得合理的加速,最简单的方法是什么?

But I'm dealing with big images, and unpacking that many items into function arguments seems to be noticeably slow. What's the simplest thing I can do to get a reasonable speedup?

我只是将其转换为元组作为中间步骤,因此,如果不必要,那就更好了.

I'm only converting to a tuple as an intermediate step, so if it's unnecessary, all the better.

推荐答案

您可以先构建未初始化的数组:

You can first build an uninitialized array:

pixarray = (ctypes.c_int * (w_px * h_px))()

,然后将图像的内容复制到其中:

and then copy the image's contents into it:

# dylib in MacOSX, cdll.wincrt in Win, libc.so.? in Unix, ...
clib = ctypes.CDLL('libc.dylib')

_ = clib.memcpy(pixarray, im.tostring(), w_px * h_px * 4)

memcpy的返回值是您不关心的地址,因此我通过将其分配为名称单个下划线"来吞噬"它(按照惯例,这意味着我不在乎这个";- ).

The return value of memcpy is an address you don't care about, so I "swallowed" it by assigning it to name "single underscore" (which by convention means "I don't care about this one";-).

编辑:正如@Mu Mind在评论中指出的那样,可以有效地简化后一个片段以使用

Edit: as @Mu Mind points out in a comment, the latter fragment can usefully be simplified to use ctypes.memmove without the need to go platform-dependent to ferret out clib: just do

_ = ctypes.memmove(pixarray, im.tostring(), w_px * h_px * 4)

这篇关于有效地将字符串(或元组)转换为ctypes数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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