vs环境配置:
1,将python安装路径中的include和libs文件夹路径添加至vs属性中。(也可以将这两个文件夹拷贝到vs工程下)
2,在属性的输入中输入python36.lib(libs文件夹下)的路径(debug下为python36_d.lib,没有debug就复制python36.lib再改名字就行)
python代码
def hello_c():
print("I am python")
if __name__ == '__main__':
hello_c()
C++代码
#include <iostream>
#include <Python.h>
#include <windows.h>
using namespace std;
int main()
{
string wxid = "D:\\Anaconda3\\envs\\python36";//设置homepython,电脑中python的安装路径
std::wstring widstr = std::wstring(wxid.begin(), wxid.end());
wchar_t * wxids = new wchar_t[wxid.size()];
swprintf(wxids, 100, L"%S", wxid.c_str());
Py_SetPythonHome(wxids);
Py_Initialize();
if (!Py_IsInitialized())
{
cout << "initialize failed" << endl;
Py_Finalize();
}
PyObject *pModule;
PyObject*pFunc = NULL;
PyObject*pArg = NULL;
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");//设置python模块,搜寻位置,文件放在.cpp文件一起
pModule = PyImport_ImportModule("hello_C");//Python文件名
if (!pModule) {
cout << "py文件导入失败" << endl;
Py_Finalize();
}
else {
pFunc = PyObject_GetAttrString(pModule, "hello_c");//Python文件中的函数名
if (!pFunc) {
cout << "函数导入失败" << endl;
Py_Finalize();
}
PyEval_CallObject(pFunc, NULL);//调用函数
system("pause");
return 0;
}
}
把python代码放在工程路径中