你如何从 sip.voidptr (QImage.constBits()) 到 ctypes void 或 char 指针?

Shi*_*ond 6 python qt ctypes pyqt python-3.x

我正在使用 python,当然你不能很快地遍历大图像的每个像素,所以我遵循 C DLL。

我想做这样的事情:

img = QImage("myimage.png").constBits()
imgPtr = c_void_p(img)
found = ctypesDLL.myImageSearchMethod(imgPtr, width, height)
Run Code Online (Sandbox Code Playgroud)

但是这一行 imgPtr = c_void_p(img) ylds

builtins.TypeError:无法转换为指针

我不需要修改位。请教我你在这方面的绝地方法。

p-a*_*l-o 5

如前所述这里sip.voidptr.__int__()方法

以整数形式返回地址

虽然c_void_p 文档

构造函数接受一个可选的整数初始值设定项。

因此,您应该能够构建c_void_psip.voidptr.__int__()方法的返回值传递给其构造函数的方法:

imgPtr = c_void_p(img.__int__())
Run Code Online (Sandbox Code Playgroud)

我以这种方式测试了这个解决方案:

from PyQt5 import QtGui
from ctypes import *

lib = CDLL("/usr/lib/libtestlib.so")

image = QtGui.QImage("so.png")
bits = image.constBits()
bytes = image.bytesPerLine()
lib.f(c_void_p(bits.__int__()), c_int(image.width()), c_int(image.height()), c_int(bytes))
Run Code Online (Sandbox Code Playgroud)

它适用于以下功能:

#include <cstdio>
#include <QImage>
extern "C" {

    void f(unsigned char * c, int width, int height, int bpl)
    {
        printf("W:%d H:%d BPL:%d\n", width, height, bpl);
        QImage image(c, width, height, bpl, QImage::Format_RGB32);
        image.save("test.bmp");
    }
}
Run Code Online (Sandbox Code Playgroud)