Linux下Python与C++混合编程
最近在做一个CUDA的项目,记录下学习心得.
系统
Linux 3.11.0-19-generic #33-Ubuntu x86_64 GNU/Linux
C++调用Python
Python模块代码:
1 #!/usr/bin/python 2 #Filename:TestModule.py 3 def Hello(s): 4 print "Hello World" 5 print s 6 7 def Add(a, b): 8 print 'a=', a 9 print 'b=', b 10 return a + b 11 12 class Test: 13 def __init__(self): 14 print "Init" 15 def SayHello(self, name): 16 print "Hello,", name 17 return name
C++代码:
1 #include<iostream> 2 #include<Python.h> 3 using namespace std; 4 int main(int argc, char* argv[]) 5 { 6 //初始化python 7 Py_Initialize(); 8 9 //直接运行python代码 10 PyRun_SimpleString("print 'Python Start'"); 11 12 //引入当前路径,否则下面模块不能正常导入 13 PyRun_SimpleString("import sys"); 14 PyRun_SimpleString("sys.path.append('./')"); 15 16 //引入模块 17 PyObject *pModule = PyImport_ImportModule("TestModule"); 18 //获取模块字典属性 19 PyObject *pDict = PyModule_GetDict(pModule); 20 21 //直接获取模块中的函数 22 PyObject *pFunc = PyObject_GetAttrString(pModule, "Hello"); 23 24 //参数类型转换,传递一个字符串。将c/c++类型的字符串转换为python类型,元组中的python类型查看python文档 25 PyObject *pArg = Py_BuildValue("(s)", "Hello Charity"); 26 27 //调用直接获得的函数,并传递参数 28 PyEval_CallObject(pFunc, pArg); 29 30 //从字典属性中获取函数 31 pFunc = PyDict_GetItemString(pDict, "Add"); 32 //参数类型转换,传递两个整型参数 33 pArg = Py_BuildValue("(i, i)", 1, 2); 34 35 //调用函数,并得到python类型的返回值 36 PyObject *result = PyEval_CallObject(pFunc, pArg); 37 //c用来保存c/c++类型的返回值 38 int c; 39 //将python类型的返回值转换为c/c++类型 40 PyArg_Parse(result, "i", &c); 41 //输出返回值 42 printf("a+b=%d\n", c); 43 44 //通过字典属性获取模块中的类 45 PyObject *pClass = PyDict_GetItemString(pDict, "Test"); 46 47 //实例化获取的类 48 PyObject *pInstance = PyInstance_New(pClass, NULL, NULL); 49 //调用类的方法 50 result = PyObject_CallMethod(pInstance, "SayHello", "(s)", "Charity"); 51 //输出返回值 52 char* name=NULL; 53 PyArg_Parse(result, "s", &name); 54 printf("%s\n", name); 55 56 PyRun_SimpleString("print 'Python End'"); 57 58 //释放python 59 Py_Finalize(); 60 getchar(); 61 return 0; 62 }
编译:
g++ -I/usr/include/python2.7 PythonWithCpp.cpp -lpython2.7
运行结果:
Python Start Hello World Hello Charity a= 1 b= 2 a+b=3 Init Hello, Charity Charity Python End
Python调用C++
C++代码:
1 //用C++必须在函数前加extern "C" 2 extern "C" int Add(int a,int b) 3 { 4 return a+b; 5 }
编译:
1 g++ -c -fPIC LibPythonTest.cpp 2 g++ -shared LibPythonTest.o -o LibPythonTest.so
Python代码:
1 #!/bin/python 2 #Filename:PythonCallCpp.py 3 from ctypes import * 4 import os 5 libPythonTest = cdll.LoadLibrary('./LibPythonTest.so') 6 print libPythonTest.Add(1,1)
运行:
1 python PythonCallCpp.py
运行结果:
2