环境:VS2017,anaconda中python3.7.7
配置结果:debug x64
环境配置
包含目录D:\anaconda3\include
库目录:D:\anaconda3\libs
依赖项:python37_d.lib
1.项目右击-》属性-》c/c+±》附加包含目录
2.项目右击-》属性-》链接器-》常规-》附加库目录
2.项目右击-》属性-》链接器-》输入-》附加依赖项
代码
使用c++调用python代码存在两种方法
1.使用PyRun_SimpleString命令,(这种形式最简单,好用,但是变量不好传递,只能够传递文件名,利于实时性要求不高)
#include <Python.h>
#include<iostream>
using namespace std;
int main()
{
Py_SetPythonHome(L"D:/anaconda3");//这里地址一定要写对啊!
/** 添加python.exe所在路径,不添加在运行时出现
Fatal Python error: initfsencoding: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'**/
Py_Initialize();//使用python之前,要调用Py_Initialize();这个函数进行初始化
if (!Py_IsInitialized())
{
printf("初始化失败!");
return 0;
}
else {
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");//这一步很重要,修改Python路径
PyRun_SimpleString("import Sample");
char *temp = "print(Sample.hello('52,589'))";
PyRun_SimpleString(temp);
}
Py_Finalize();//调用Py_Finalize,这个根Py_Initialize相对应的。
return 0;
}
2.使用PyImport_ImportModule,PyObject_GetAttrString,Py_BuildValue模型传递命令,(这种形式有点繁琐,但是变量传递简单,利于实时性要求高)
#include <Python.h>
#include<iostream>
#include <string>
using namespace std;
int main()
{
Py_SetPythonHome(L"D:/anaconda3");//这里地址一定要写对啊!
// /** 添加python.exe所在路径,不添加在运行时出现
// Fatal Python error: initfsencoding: unable to load the file system codec
// ModuleNotFoundError: No module named 'encodings'**/itialize();//使用python之前,要调用Py_Initialize();这个函数进行初始化
if (!Py_IsInitialized())
{
printf("初始化失败!");
return 0;
}
else {
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");//这一步很重要,修改Python路径
PyObject * pModule = NULL;//声明变量
PyObject * pFunc = NULL;// 声明变量
PyRun_SimpleString("import Sample");
pModule = PyImport_ImportModule("Sample");//这里是要调用的文件名hello.py
if (pModule == NULL)
{
cout << "没找到该Python文件" << endl;
}
else {
//进行整数传参,返回值
pFunc = PyObject_GetAttrString(pModule, "add");//这里是要调用的函数名
PyObject* args = Py_BuildValue("(ii)", 28, 103);//给python函数参数赋值
PyObject* pRet = PyObject_CallObject(pFunc, args);//调用函数
int res = 0;
PyArg_Parse(pRet, "i", &res);//转换返回类型
cout << "整数返回值:" << res << endl;//输出结果
//进行字符传参,返回值
pFunc = PyObject_GetAttrString(pModule, "hello");//这里是要调用的函数名
args = Py_BuildValue("ss", "28", "103");//给python函数参数赋值
pRet = PyObject_CallObject(pFunc, args);//调用函数
char* res2;
PyArg_Parse(pRet, "s", &res2);//转换返回类型
cout << "字符串返回值:" << res2 << endl;//输出结果
//printf("%s\n", res);
}
Py_Finalize();//调用Py_Finalize,这个根Py_Initialize相对应的。
}
return 0;
}
对应python代码
import numpy as np
def hello(x='12',y='1'):
if not isinstance(x, str):
x="helloxx! {}".format(x)
else:
x=("helloxx!"+x)
return x
def add(a, b):
return a+b
# def
if __name__ == '__main__':
xx = np.array([1, 23, 4156])
print(xx)
zz=hello('52889898')
print(zz)
错误
1.Fatal Python error: initfsencoding: unable to load the file system codec
ModuleNotFoundError: No module named ‘encodings’
Current thread 0x000054b8 (most recent call first):
解决方法:加上Py_SetPythonHome(L"D:/anaconda3");
传递参数类型
参考1:2Vs2017调用Python函数,2VS2017
参考2:这里要隆重的写一下C++调用python遇到的各种坑,搞了好久,终于成功了!