C++调用 python 函数及返回值的处理【元组,字符串...】
2014-03-21 15:38
806 查看
http://www.cnblogs.com/DxSoft/archive/2011/04/01/2002676.html
Python 脚本 py_test.py :
C 函数:
Python 脚本 py_test.py :
#coding:utf-8 def get_int( ): a = 10 b = 20 return a + b def get_str( s1, s2 ): #return s1 + s2 #return 'Hello , TY' return ('Hello, World', 10, 20)
C 函数:
#include <stdio.h> #include <stdlib.h> #include <python.h> #pragma comment(lib, "python27_d.lib") int main() { PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pRetVal; Py_Initialize(); if (!Py_IsInitialized()) return -1; //load py script filename PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); pName = PyString_FromString("py_test");// py_test.py pModule = PyImport_Import(pName); if (!pModule){ printf("cant find py_test.py"); getchar(); return -1; } pDict = PyModule_GetDict(pModule); if (!pDict) return -1; //find function name pFunc = PyDict_GetItemString(pDict, "get_str"); if (!pFunc || !PyCallable_Check(pFunc)){ printf("cant find function [add]"); getchar(); return -1; } //push args to stack pArgs = PyTuple_New(2); PyTuple_SetItem(pArgs, 0, Py_BuildValue("s", "Hello, ")); PyTuple_SetItem(pArgs, 1, Py_BuildValue("s", "C_Python")); //call python function pRetVal = PyObject_CallObject(pFunc, pArgs); if (pRetVal == NULL){ printf("CalllObject return NULL"); return -1; } char* ret_str; int w = 0 , h = 0; //解析元组 PyArg_ParseTuple(pRetVal, "s,i,i",&ret_str, &w, &h); printf("%s, %d, %d\n", ret_str, w, h); //解析字符串 //printf("function return value:%s\r\n", PyString_AsString(pRetVal)); Py_DECREF(pName); Py_DECREF(pArgs); Py_DECREF(pModule); Py_DECREF(pRetVal); //close python Py_Finalize(); getchar(); return 0; }
相关文章推荐
- python 调用 DLL 的函数,返回的字符串数组的食用方法
- C#调用C++DLL的小总结8---C++Dll中函数返回字符串指针
- python 调用 DLL 的函数,返回的字符串数组的食用方法
- C++对象模型之编译器如何处理函数返回一个对象
- python字符串处理rstrip()、lstrip()、strip()函数使用
- 使用自己的Python函数处理Protobuf中的字符串编码
- c++(字符串处理函数)
- C/C++ 字符串处理函数(转载)
- Python内置的字符串处理函数整理
- c++调用python函数
- C、C++字符串处理函数
- C++中字符串处理函数
- 如何在C++中使用类似python的字符串split()函数
- Python字符串内建处理函数
- python 字符串处理函数
- Windows下QT中用C++调用Python之二 - 编译BUG处理
- Python 中的字符串处理函数
- c++字符串处理函数及其用法
- [C/C++] 字符串处理函数 strstr 与 strncpy
- Python内置的字符串处理函数整理