在C++中调用Python接口
2015-12-05 21:04
501 查看
参照如下博客可以看看写好的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代码:
pytest.py代码如下:
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
相关文章推荐
- C++继承中的名字查找
- C语言程序设计-第5章 循环结构程序设计
- C语言程序设计-第4章 选择结构程序设计
- C语言程序设计-第3章 最简单的C程序设计-顺序程序设计
- leetcode 312 : Burst Balloons
- VC++回顾----多线程
- 大数加法——HOJ1002
- C++ STL
- c中动态与静态二维数组
- C++
- C++ STL基本容器比较
- 【五】ODB - C++ 表单列函数count、min、max(V1.0)
- C语言成长学习题(一)
- C++学习笔记32——构造函数
- C语言常见错误
- C语言指针理解patr1
- MinGW 创建的程序或 DLL 脱离 libgcc-xx-xx.dll 和 libstdc++-x.dll 运行库的方法
- C++虚函数
- C++虚函数
- Java 通过 Jni 调用 C++代码