Threading module and embedded python

Eko palypse ekopalypse at gmail.com
Wed Apr 15 08:30:38 EDT 2020


Hi everyone,

the following happens on Windows7 x64 and Python37 x64

I have a plugin DLL for a C++ application in which Python37 is embedded.
The plugin itself works, except when I want to use the threading module.

If I start a Python script in my plugin which uses the threading module
I can verify via ProcessExplorer that the thread is started,
but it doesn't do anything (??) and the c++ application doesn't really do anything anymore either.

Only when I stop the C++ Applikation, the thread becomes active for a short time.
Verified with logging module over time print-outs.

Apparently I did not understand everything about threads and embedded python.

Any idea what I'm doing wrong?


The whole thing is initialized by the DllMain routine.


BOOL APIENTRY DllMain( HANDLE hModule,
                       DWORD  reasonForCall,
                       LPVOID /* lpReserved */ )
{
    switch ( reasonForCall )
    {
        case DLL_PROCESS_ATTACH:
            if (!Py_IsInitialized())
            {
                PyImport_AppendInittab("Npp", &PyInit_Npp);
                Py_InitializeEx(0);
                PyEval_InitThreads();  //<- this shouldn't be needed as I understand that it is called by Py_InitializeEx anyway
            }
            PyImport_ImportModule("Npp");
            break;
        case DLL_PROCESS_DETACH:
            Py_Finalize();
            break;

        case DLL_THREAD_ATTACH:
            break;

        case DLL_THREAD_DETACH:
            break;
    }

    return TRUE;
}

and the code in the plugin which executes the python scripts is this

cdef void run_code():
    try:
        global_dict = globals()
        if '__name__' not in global_dict or global_dict['__name__'] != '__main__':
            global_dict.update({"__name__": "__main__",})
        exec(compile(editor.getText(), '<string>', 'exec'), global_dict)
        
    except Exception:
        MessageBoxW(nppData._nppHandle,
                    traceback.format_exc(),
                    'RUN CODE EXCEPTION',
                    0)  

I don't know if this is important, but the DLL is generated by Cython.

Thank you for reading and stay healthy

Eren


More information about the Python-list mailing list