问题
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
回答1:
I managed to work past this problem. It seems that some modules have problems when their initialization routines are called more than once, and numpy
is 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
回答2:
Similar problem happens with pyHook
and pyxhook
library. Spent long time to figure out the reason of crash for those two modules but no clue available online. Now I am finding it is happening with numpy
too. Hoping this one time Py_Finalize()
will solve both of my problems.
The problem is solved after disabling python thread support in my embedded interpreter code by commenting the followings. By the way I am running the interpreter already in a POSIX thread created by my C code.
//PyEval_InitThreads();
//gstate = PyGILState_Ensure();
//PyGILState_Release(gstate);
Now I can run my py.script with numpy and pyHook many times. However it will cause the following error message at the end of the C code if the module thread
is imported in python script directly or by any other imported module.
Exception KeyError: KeyError(14288,) in <module 'threading' from 'C:\python27\Lib\threading.pyc'> ignored
Still I feel It needs a better solution.
来源:https://stackoverflow.com/questions/23134820/unhandled-exception-at-multiarray-pyd-the-2nd-time-the-program-runs