MikeRand
MikeRand

Reputation: 4838

Using Python object exported from DLL in an exe

I have a two-part event generator:

pyglobalexe (a stub to simulate events):

#pragma comment(lib, "pyglobalextension.lib")

#include <Python.h>

__declspec(dllimport) PyObject* PyInit_pyglobalextension;
__declspec(dllimport) PyObject* event_queue;

int main() {
    int i;
    for(i=0; i<10; i++) {
        PyObject_CallMethod(event_queue, "put", "O", PyLong_FromLong(i*2));
    }
    return 0;
}

pyglobalextension

#include <Python.h>

__declspec(dllexport) PyObject *event_queue = NULL;

static PyObject *
set_queue(PyObject *self, PyObject *args)
{
    PyObject *temp;

    if(!PyArg_ParseTuple(args, "O", &temp)){
        return NULL;
    }
    Py_XINCREF(temp);
    Py_XDECREF(event_queue);
    event_queue = temp;
    Py_INCREF(Py_None);
    return Py_None;
}

static PyMethodDef PyGlobalExtensionMethods[] = {
    {"set_queue",  set_queue, METH_VARARGS, "Set a queue global."},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef PyGlobalExtensionModule = {
   PyModuleDef_HEAD_INIT,
   "pyglobalextension",
   NULL,
   -1,
   PyGlobalExtensionMethods
};

PyMODINIT_FUNC
PyInit_pyglobalextension(void)
{
    return PyModule_Create(&PyGlobalExtensionModule);
}

Both files compile fine. pyglobalexe.exe crashes on the PyObject_CallMethod call. What do I have to change so that I can use the event_queue global from pyglobalextension in pyglobalexe?

===EDIT===

Sorry, should have made the use case more clear.

Command prompt 1 (running python.exe)

>>> import pyglobalextension
>>> from queue import Queue
>>> q = Queue()
>>> pyglobalextension.set_queue(q)

Command prompt 2 (once I'm done in command prompt 1).

$> pyglobalexe

I was hoping that I'd be able to go back to command prompt 1 and q.get() 10 numbers.

Upvotes: 1

Views: 318

Answers (1)

Cat Plus Plus
Cat Plus Plus

Reputation: 129894

  1. event_queue will be NULL, because nothing has called set_queue before you do CallMethod.
  2. PyInit_... is a function, not a variable; and you don't call it, so the module and the set_queue don't even exist.

Ad. edit:

Above still stands. What you're doing requires interprocess communication, simple global variable won't do what you want to do (both processes have their own copy of it — only code of the DLL may be shared, data is not — and in pyglobalexe, it's NULL).

Upvotes: 2

Related Questions