在C / C ++中创建已包装库的Python对象?

时间:2012-01-31 18:16:50

标签: python c windows wrapper

是否可以从C指针为C / C ++中的pywin32PyOpenGL等已包装的库创建Python包装器?

您可以为我填写/更正该代码段吗?

#include <windows.h>
#include <the_magical_pywin32_header.h>
PyObject* PyObject_fromHWND(HWND window) {
    // ...
}

1 个答案:

答案 0 :(得分:1)

#include <windows.h>
#include <Python.h>
#include <pythonwin/win32win.h> // Make sure this is in the include path

static PyObject *g_pModule = NULL;

PyObject* PyObject_fromHWND(HWND window)
{
    PyObject *pName, *pArgs, *pValue;
    if (g_pModule == NULL) {
        char name[] = "pythonwin/win32gui.py";  // Replace with the full path
        pName = PyString_FromString(name);
        g_pModule = PyImport_Import(pName);
        py_DECREF(pName);
        if (g_pModule == NULL) {
            // Report an error
        }
    }
    pArgs = PyTuple_New(1);
    pValue = PyInt_FromLong(static_cast<long>(window));
    PyTuple_SetItem(pArgs, 0, pValue);
    PyObject *pWindow = PyCWnd::CreateWindowFromHandle(g_pModule, pArgs);
    Py_DECREF(pValue);
    Py_DECREF(pArgs);
    return pWindow;
}