windows C++嵌入python. No module named 'numpy.core._multiarray_umath’报错
问题:
Traceback (most recent call last):
File "D:\Programs\Python\Python38\lib\site-packages\numpy\core\__init__.py", line 22, in <module>
from . import multiarray
File "D:\Programs\Python\Python38\lib\site-packages\numpy\core\multiarray.py", line 12, in <module>
from . import overrides
File "D:\Programs\Python\Python38\lib\site-packages\numpy\core\overrides.py", line 7, in <module>
from numpy.core._multiarray_umath import (
ModuleNotFoundError: No module named 'numpy.core._multiarray_umath'
工程
CMakeList.txt文件
cmake_minimum_required(VERSION 3.4.1)
set(TARGET_NAME "test")
project(${TARGET_NAME})
...
find_package(Python3 COMPONENTS Interpreter Development REQUIRED)
include_directories(${Python3_INCLUDE_DIRS})
file(GLOB_RECURSE SOURCE_FILE "src/*.cpp" "src/*.h")
add_executable( ${TARGET_NAME} ${SOURCE_FILE})
target_link_libraries(${TARGET_NAME} ${Python3_LIBRARIES})
...
set_property(TARGET ${TARGET_NAME} PROPERTY VS_DEBUGGER_WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/bin)
问题原因
windows下debug工程引用到了python3.x_d.lib,也就是debug版的python库。引用numpy又引入了numpy.core._multiarray_umath。
使用everything搜索一下,是存在_multiarray_umath文件的。但是不确定这个后缀cp38-win_amd64是否正常,网上查下,发现cp38代表python3.8。win_amd64就不用说了。
继续搜资料…
发现是debug版本的python,引用库的后缀名也带了_d标识。
import importlib.machinery
print(importlib.machinery.all_suffixes())
输出结果:
['.py', '.pyw', '.pyc', '_d.cp38-win_amd64.pyd', '.pyd']
解决方案
直接引用python的release库版本
步骤一:
target_link_libraries(${TARGET_NAME} ${Python3_LIBRARIES})
改为
target_link_libraries(${TARGET_NAME} ${Python3_LIBRARY_RELEASE})
直接引用release库
本来以为这一步就可以了,结果发现一直报错 “python38_d.lib”。。。
无语中。。。
继续查…
发现pyconfig.h 里如果声明了_DEBUG 就会直接引用了python38_d.lib,于是有了步骤二。
注:试过其它版本的python,没有步骤二这个问题,所以无需步骤二
步骤二:
#ifdef _DEBUG
#undef _DEBUG
#include <Python.h>
#define _DEBUG
#else
#include <Python.h>
#endif
引用python头文件的时候
你学废了吗!?