Python calling DLL calling Python, "WindowsError: exception: access violation reading 0x00000004"
Question: I have an application written in Python.

The application calls some functions in the dll (using ctypes) that calls some
functions from the python C API to load and run some functions in a
(different) python module. This causes `WindowsError: exception: access
violation reading 0x00000004` Some cout debugging tells me that the access
violation happens on a call to the Python C API.

I know the DLL successfully loads the python module, running to completion
when I test it as a stand alone .exe but when it is run from the python
application it gives this access violation error.

I first though that maybe I should use Py_NewInterpreter in the DLL to create
a new separate space for these python module functions to run. This would seem
convienent as there is no need for the application and the modules runs by the
DLL to share any data.
<http://docs.python.org/2/c-api/init.html#Py_NewInterpreter>

However my initial tests with Py_NewInterpreter have proved unsuccessful
simply making further errors and crashing.

So my question is how should I implement this/what do I need to do make the
DLL load of the python modules work?


Answer: This looks like dereferencing a null pointer, i.e. a pointer to a
structure/class is null and you are reading a subobject at offset 4. Sprinkle
a few assert()s throughout your code to make sure you don't miss any null
pointer. Note also that the Python C API regularly returns null in case of an
exception.

That said, you have a Python program importing a DLL via ctypes. This DLL in
turn embeds a Python interpreter via Python's C API. Right? If I'm not
mistaken, that effectively gives you two interpreter instances in one process.
The problem there is that any global objects are shared between the two and
that this might not be coordinated.

What I would try is to write a proper Python (wrapper) module instead of using
ctypes to import the DLL. However, there's another thing that I would do in
parallel and that is to ask on the Python user mailinglist, whether this setup
can work or not and why. There is also a news gateway in case you prefer that.

