最近在作一個CUDA的項目,記錄下學習心得.python
Linux 3.11.0-19-generic #33-Ubuntu x86_64 GNU/Linux
Python模塊代碼:ios
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++代碼: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 }
編譯:app
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
C++代碼:學習
1 //用C++必須在函數前加extern "C" 2 extern "C" int Add(int a,int b) 3 { 4 return a+b; 5 }
編譯:ui
1 g++ -c -fPIC LibPythonTest.cpp 2 g++ -shared LibPythonTest.o -o LibPythonTest.so
Python代碼:spa
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)
運行:code
1 python PythonCallCpp.py
運行結果:blog
2