Search code examples
pythonc++python-c-api

Unhandled exception at multiarray.pyd the 2nd time the program runs


I'm making a .dll plug-in in c++ and embedding python 2.7 in it.

Everything worked fine with simple .py programs until I imported a large program. The strangest thing is that the program runs with no problem the first time, but the second time an exception is raised:

Unhandled exception at 0x6731ADA1 (multiarray.pyd) in EuroScope.exe: 0xC0000005: Access violation writing location 0x00000001.

(The Lib/Dll folders and modules are all copied to the .exe folder)

I've searched the web and there are a couple of persons with the same error but the solutions that worked for them don't for me. For example here

I know this is a very specific error but I'm hoping that someone out there has already managed to work past it. I won't post the code here because i think it's irrelevant for this bug and also because it's way too long

Edit: I managed to see the problem is specifically in import numpy


Solution

  • I managed to work past this problem. It seems that some modules have problems when their initialization routines are called more than once, and numpyis one of those. The solution is to call Py_Finalize() only once at the very end of the program. Py_Initialize() can be called as many times as you want, as if Python is already initialized, Py_Initialize() is a non-op ...

    And also, discovered that this solution turns the application faster since python doesn't need to restart every time there's a call to some of its function.

    More information about it here