问题:执行完python代码后,调用Py_Finalize
,再调用Py_Initialize
,重新执行python代码,但第一行PyRun_SimpleString("import cv2")
就报错
0x00007FF9853BC569 (_multiarray_umath.cp37-win_amd64.pyd)处(位于 mytest.exe 中)引发的异常:
0xC0000005: 写入位置 0x000000000000000A 时发生访问冲突。
这是C:\ProgramData\Anaconda3\Lib\site-packages\numpy\core下的一个pyd文件,opencv用到这个模块。显然,是第二次import cv2
引发改异常,说明Py_Finalize
并没有正确释放cv2的资源。经过查看官方文档,发现的确是Py_Finalize
的问题:Py_FinalizeEx() - Bugs and caveats
The destruction of modules and objects in modules is done in random order; this may cause destructors (__del__() methods) to fail when they depend on other objects (even functions) or modules. Dynamically loaded extension modules loaded by Python are not unloaded. Small amounts of memory allocated by the Python interpreter may not be freed (if you find a leak, please report it). Memory tied up in circular references between objects is not freed. Some memory allocated by extension modules may not be freed. Some extensions may not work properly if their initialization routine is called more than once; this can happen if an application calls Py_Initialize() and Py_FinalizeEx() more than once.
因此,应用程序里不要多次执行Py_Finalize
、Py_Initialize
,全局只能出现一对该操作