visual stdio2019 c++调用python混合编程
1.Python环境的搭建
关于环境创建可以参考https://blog.csdn.net/qq_36559788/article/details/123174309
这里python我用的是anaconda里的python38,并且没有debug库,所以我只用了release库
在vs中设置项目属性,添加包含目录以及附加库目录,注意都是在release模式下添加的
2.测试
在main.cpp中添加头文件
#include<Python.h>
添加代码
int main() {
Py_Initialize();
PyRun_SimpleString("print ('hello')");
PyRun_SimpleString("import numpy as np");
Py_Finalize();
system("pause");
return 0;
}
编译运行一下,报错:
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
解决方法: 参考https://blog.csdn.net/qq_43302566/article/details/121537908
在环境变量中添加PYTHONHOME和PYTHONPATH的路径,但是需要重启电脑,环境变量才能生效!!!!
再次运行,新的报错信息:
ImportError: DLL load failed while importing _multiarray_umath: 找不到指定的模块。
我参考了https://www.cnblogs.com/mrlayfolk/articles/15621645.html这篇博客,但是没有用,搞了一下午,最终还是重装了虚拟环境,将numpy从1.24降为了1.19, 这个问题就可以解决了!!
以下这篇博客的问题同样也是这个解决方法,在此做一个记录
https://blog.csdn.net/qq_39244214/article/details/125010376
很无语,解决了numpy问题之后,pytorch和opencv-python还是有问题,报错belike:
又搞了一下午和一晚上,尝试了很多方法,只有将opencv版本降级,才能成功import cv2,但是torch还是不行!!!好无语!!!