Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you go from a sip.voidptr (QImage.constBits()) to a ctypes void or char pointer?

I'm using python and of course you can't loop through every pixel of a large image very quickly, so I defer to a C DLL.

I want to do something like this:

img = QImage("myimage.png").constBits()
imgPtr = c_void_p(img)
found = ctypesDLL.myImageSearchMethod(imgPtr, width, height)

But this line imgPtr = c_void_p(img) yelds

builtins.TypeError: cannot be converted to pointer

I don't need to modify the bits. Please teach me your Jedi ways in this area.

like image 271
PurpleHaze Avatar asked Dec 07 '17 07:12

PurpleHaze


1 Answers

As stated here, sip.voidptr.__int__() method

returns the address as an integer

while c_void_p documentation says

The constructor accepts an optional integer initializer.

So you should be able to build a c_void_p passing the return value of sip.voidptr.__int__() method to its constructor:

imgPtr = c_void_p(img.__int__())

I tested this solution this way:

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))

Which works fine with a function like:

#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");
    }
}
like image 199
p-a-o-l-o Avatar answered Oct 05 '22 23:10

p-a-o-l-o