JHo*_*lta 0 c python arrays ctypes bitmap
目前正在尝试将C用于以前在python(pypy)中完成的工作.我想我会尝试用C语言编写它(以获得最佳速度),并使用ctypes进行通信.
现在我想做的是从Bitmap(bmp文件)中获取pixelbuffer,将其发送到C函数,该函数将原始缓冲区转换为R,G,B值的平面数组并将其返回到python.但是当我试图将"缓冲区"转换为R,G,B值时,我陷入了困境.在python中,我只需使用"struct"模块:B,G,R = struct.unpack('<BBB', buffer[i:i+3])
我该如何在C中做同样的事情?
蟒蛇:
from bmplib import Bitmap
import ctypes
lib = ctypes.CDLL('_bitmap.dll')
bmp = Bitmap()
bmp.open('4x4.bmp')
buf = bmp._rawAsArray() #Returns a array.array() of char (raw pixel-data)
addr, count = buf.buffer_info()
lib.getData.argtypes = []
arr = ctypes.cast(addr, ctypes.POINTER(ctypes.c_char))
lib.getData(arr, count) #Does not return anything yet..
Run Code Online (Sandbox Code Playgroud)
C尝试转换像素失败:
#include <stdio.h>
void getData(char *, const int);
void getData(char * array, const int length) {
int i = 0;
while(i < length) {
/* ----- Clearly wrong as i got some HUGE number----- */
printf("%d, ", ((int *) array)[i] << 8); //B
printf("%d, ", ((int *) array)[i+1] << 8); //G
printf("%d\n", ((int *) array)[i+2] << 8); //R
i += 3;
}
//return total;
}
Run Code Online (Sandbox Code Playgroud)
目前还不清楚你收到图像的格式char * array.假设每个数组元素有一个字节,则不需要进行任何移位:
while(i < length) {
printf("%d, ", (unsigned int)array[i++]); //B
printf("%d, ", (unsigned int)array[i++]); //G
printf("%d\n", (unsigned int)array[i++]); //R
}
Run Code Online (Sandbox Code Playgroud)
但请记住,BMP图像可以为每一行添加一些填充,因此仅当array对应于单行length且不包括填充时才会起作用.