最近需要使用别人开源的一份python代码,而我的主程序是C++, 想过去改写那份python代码,但是感觉比较麻烦,所以就想尝试一下C++ calling python! 但是非常坑,我搞了一天,查了很多资料才搞定。
环境描述
OS:win10, IDE: VS2015
Python env: anaconda (python2.7, python3.7)
VS配置:Debug模式
VC++目录 > 包含目录: D:\program_softwares\anaconda3\include
VC++目录 > 库目录:D:\program_softwares\anaconda3\libs
链接器 > 附加依赖项: python37.lib
Python程序
import numpy as np
def hello_np():
arr = np.random.rand(5,2)
print('hello c++! I am a snake, send you an array:')
return arr
C++程序
int main(){
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
Py_IsInitialized();
PyObject* pModule = PyImport_ImportModule("hello2python"); //参数为Python脚本的文件名
if (pModule){
PyObject* pFunc = PyObject_GetAttrString(pModule, "hello"); //获取函数
PyObject* ret = PyEval_CallObject(pFunc, NULL); //执行函数
}
else
PyErr_Print();
Py_Finalize();
return 0;
}
运行报错如下:
Traceback (most recent call last):
File “D:\program_softwares\anaconda3\lib\site-packages\numpy\core_init_.py”, line 22, in
from . import multiarray
File “D:\program_softwares\anaconda3\lib\site-packages\numpy\core\multiarray.py”, line 12, in
from . import overrides
File “D:\program_softwares\anaconda3\lib\site-packages\numpy\core\overrides.py”, line 7, in
from numpy.core._multiarray_umath import (
ModuleNotFoundError: No module named 'numpy.core._multiarray_umath’
最终查到一条很有用的信息如下:
Open Visual Studio and create a new C++ “Win32 Console Application” project. Before you can call Python code you need to tell Visual Studio how to find Python. Before doing this change the build mode from “Debug” to “Release”. If you attempt to build a Visual Studio project that calls Python code in Debug mode the build will fail because, in debugging mode, Visual Studio will look for a library file that does not exist. The reason why this file did not exist on my machine is because the Windows Python installer did not install a version of Python compiled in Debug mode. It is possible to get a version of Python built in Debug mode, but you will have to download the Python source code and build it manually. For the purposes of this blog post we will ignore this and just change to Release mode.
大致意思是说,不能选debug,因为选debug的话,VS要去寻找一大堆相应的debug的libs, 但是默认安装python是release的,根本找不到debug相应的库。
所以解决方案就是: 选择release。(这算什么解决方案,但我确实又尝试了debug的方法,无法搞定,甚至装了python的debug版本,依然不行!!)
参考:Calling Python Code from C++
https://blog.csdn.net/Darling100/article/details/105069669?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.channel_param