在C++中调用Python接口

这篇博客详细介绍了如何在C++项目中调用Python接口。首先,提供了G++中编译C++代码的步骤,接着展示了在Visual Studio(VS)环境中配置Python接口的方法,特别针对VS中缺少Python27_d.lib的问题给出了解决方案。最后,给出了一个实例运行的C++代码片段。
摘要由CSDN通过智能技术生成

参照如下博客可以看看写好的cpp 在G++中怎么编译:

http://blog.csdn.net/taiyang1987912/article/details/44779719

参考如下博客可以看看怎么在VS的项目中配置调用python接口

http://blog.csdn.net/c_cyoxi/article/details/23978007

参考如下地址可以解决VS中没有Python27_d.lib的问题,本人选择方法2:

http://blog.sina.com.cn/s/blog_75e9551f0101aajd.html


实例运行代码如下:

Cpp代码:

#include <Python.h>
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;

int main()
{
	Py_Initialize(); //初始化 python
	if (!Py_IsInitialized())
	{
		cout << "initialized error" << endl;
		return -1;
	}

	PyRun_SimpleString("import  sys"); // 执行 python 中的短语句
	PyRun_SimpleString("print 'come in python'");
	PyRun_SimpleString("sys.path.append('./')");

	PyObject *pName(0), *pModule(0), *pDct(0), *pFunc(0), *pArgs(0);

	pName = PyString_FromString("pytest"); //载入名为 pytest的脚本
	pModule = PyImport_Import(pName);

	if (!pModule)
	{
		cout << "can not find pytest.py" << endl;
		return -1;
	}
	else
		cout << "open Module" << endl;

	pDct = PyModule_GetDict(pModule);

	if (!pDct)
	{
		cout << "pDct error" << endl;
		return -1;
	}

	pFunc = 0;
	pFunc = PyDict_GetItemString(pDct, "add"); //找到名为 add 的函数
	if (!pFunc || !PyCallable_Check(pFunc))
	{
		cout << "pFunc error" << endl;
		return -1;
	}

	pArgs = PyTuple_New(2); //为传入形参开辟空间

	//放置传入的形参,类型说明:
	//s 字符串 , 均是C 风格的字符串
	//i 整型
	//f 浮点数
	//o 表示一个 python 对象
	PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", 1));
	PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", 2));

	PyObject_CallObject(pFunc, pArgs); 
	system("pause");
}

pytest.py代码如下:

def add(a,b):
    print "come in add"
    print a + b

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值