您的位置:首页 > 编程语言 > C语言/C++

c++调用python

2017-04-12 15:27 330 查看
环境:vs2017+python3.6 32位

1.vs建立空项目

2.将Debug改为Release;x86不变

3.项目-》属性-》c/c++-》常规-》附加包含目录-》填入python路径中的include路径

项目-》属性-》链接器-》常规-》附加库目录-》填入python路径中的libs路径

4.vs建立文件pytest.py填入下面代码

#pytest.py
#test function
def add(a,b):
print ("in python function add")
print ("a = " + str(a))
print ("b = " + str(b))
print ("ret = " + str(a+b))
return

def foo(a):

print ("in python function foo")
print ("a = " + str(a) )
print ("ret = " + str(a * a))
return

class guestlist:
def __init__(self):
print ("aaaa"  )
def p():
print ("bbbbb" )
def __getitem__(self, id):
return ("ccccc"  )
def update():
guest = guestlist()
print (guest['aa']  )

#update()


建立main.cpp填入下面代码

#include <Python.h>
#include <iostream>
using namespace std;
int main()
{
// 初始化Python
//在使用Python系统前,必须使用Py_Initialize对其
//进行初始化。它会载入Python的内建模块并添加系统路
//径到模块搜索路径中。这个函数没有返回值,检查系统
//是否初始化成功需要使用Py_IsInitialized。
Py_Initialize();

// 检查初始化是否成功
if (!Py_IsInitialized()) {
return -1;
}
// 添加当前路径
//把输入的字符串作为Python代码直接运行,返回0
//表示成功,-1表示有错。大多时候错误都是因为字符串
//中有语法错误。
PyRun_SimpleString("import sys");
PyRun_SimpleString("import os");
PyRun_SimpleString("print ('---import sys---')");
PyRun_SimpleString("sys.path.append('./')");
PyObject  *pModule, *pDict, *pFunc, *pArgs;

// 载入名为pytest的脚本
const char *a ="pytest";
pModule = PyImport_ImportModule(a);
if (!pModule) {
printf("can't find pytest.py");
getchar();
return -1;
}
pDict = PyModule_GetDict(pModule);
if (!pDict) {
return -1;
}

// 找出函数名为add的函数
printf("----------------------\n");
pFunc = PyDict_GetItemString(pDict, "add");
if (!pFunc || !PyCallable_Check(pFunc)) {
printf("can't find function [add]");
getchar();
return -1;
}

// 参数进栈
pArgs = PyTuple_New(2);

//  PyObject* Py_BuildValue(char *format, ...)
//  把C++的变量转换成一个Python对象。当需要从
//  C++传递变量到Python时,就会使用这个函数。此函数
//  有点类似C的printf,但格式不同。常用的格式有
//  s 表示字符串,
//  i 表示整型变量,
//  f 表示浮点数,
//  O 表示一个Python对象。

PyTuple_SetItem(pArgs, 0, Py_BuildValue("l", 3));
PyTuple_SetItem(pArgs, 1, Py_BuildValue("l", 4));

// 调用Python函数
PyObject_CallObject(pFunc, pArgs);

//下面这段是查找函数foo 并执行foo
printf("----------------------\n");
pFunc = PyDict_GetItemString(pDict, "foo");
if (!pFunc || !PyCallable_Check(pFunc)) {
printf("can't find function [foo]");
getchar();
return -1;
}

pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs, 0, Py_BuildValue("l", 2));

PyObject_CallObject(pFunc, pArgs);

printf("----------------------\n");
pFunc = PyDict_GetItemString(pDict, "update");
if (!pFunc || !PyCallable_Check(pFunc)) {
printf("can't find function [update]");
getchar();
return -1;
}
pArgs = PyTuple_New(0);
PyTuple_SetIt
4000
em(pArgs, 0, Py_BuildValue(""));
PyObject_CallObject(pFunc, pArgs);

Py_DECREF(pArgs);
Py_DECREF(pModule);

// 关闭Python
Py_Finalize();
getchar();
return 0;
}


报错:网上很多的代码像“代码1”可能会出现使用PyImport_Import导入自定义函数失败,pModule 返回值始终为0,原因是不确定,解决方法是替换为代码2使用
PyImport_ImportModule


代码1:

pName = PyString_FromString("pytest");
pModule = PyImport_Import(pName);


代码2:

const char * filename = "pytest";
pModule = PyImport_ImportModule(filename);


问题:PyObject_CallObject报错

解决1:debug改为release
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python visual studio