Search code examples
qtpyqt5cythonvulkan

How to send the HWND(Wind) of a qwidget from python to C++ using cython


I created a qwidget in python and the HWND produced by that is a sip.voidptr. Now if i want to send the HWND to a c++ code (via cython) to create a surface in vulkan (with vkCreateWin32SurfaceKHR) how shoud i do it?

Here is a piece of code similar to mine...

pyandcpp.pyx

cdef extern from 'AppInit.hpp':
cdef cppclass cpClass:
cpClass(int, HWND)# hinstance, hwnd

cdef class pyClass:
cdef cpClass *thisptr
def __cinit__(self, h, ptr):
\#print(str(\<HWND\> ptr))
self.thisptr = new cpClass( h,\<HWND\> ptr)#int h, void* ptr
print('Done...')

cppfile.cpp

void cpClass::cpClass(int h, HWND ptr) {
createSurdace(h, ptr);

void cpClass::createSurface(int h, HWND ptr) {
//window.createWindowSurface(instance, &surface\_);
VkWin32SurfaceCreateInfoKHR create_info = {};
create_info.sType     = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
create_info.hinstance = GetModuleHandle(nullptr);  //tried 0 also
create_info.hwnd      = ptr; //HWND\>

    if (vkCreateWin32SurfaceKHR(instance, &create_info, nullptr, &surface_)) {
        throw std::runtime_error("failed to create surface!");
    } else {
        throw std::runtime_error("successfull in create surface!");
    }

}

Main.py


class HelloTriangleApplication(QWidget):

    def __init__(self, parent):
        super(HelloTriangleApplication, self).__init__(parent)
        
        self.parent = parent
        pyClass(0, self.winId())

I tried <void*> to convert sip.voidptr to cpp voidptr but it didnt work. @user1051003 asked the same question in here but there were no answers.


Solution

  • sip.voidptr has an __int__ method which allows you to get the address represented as a Python integer. Python integers can easily be cast (in Cython) to a C integer, and then to a pointer type.

    So something like

    from libc.stdint cimport uintptr_t # unsigned int, big enough to hold a pointer
    
    cdef void* convertSipVoidPtrToCVoid(sipObj):
        return <void*><uintptr_t>(int(sipObj))