歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python與C/C++ 模塊相互調用

Python與C/C++ 模塊相互調用

日期:2017/3/1 11:15:11   编辑:Linux編程
Python調用C動態鏈接庫
Python調用C庫很簡單,不經過任何封裝打包成so,再使用python的ctypes調用即可。
<test.cpp 生成動態庫的源文件>
  1. #include <stdio.h>
  2. extern "C" {
  3. void display() {
  4. printf("This is Display Function\n");
  5. }
  6. }
  7. g++ test.cpp -fPIC -shared -o libtest.so

<call.py 調用動態庫的源文件>

  1. import ctypes
  2. so = ctypes.CDLL("./libtest.so")
  3. so.display()

這裡需要注意的是:使用g++編譯生成動態庫的代碼中的函數 或者 方法時, 需要 使用extern "C"來進行編譯

Python調用C++(含類,重載)動態鏈接庫
但是調用C++的so就有點麻煩了,網上找了下,大部分都是需要extern "C" 來輔助,也就是說還是只能調用C函數 不能直接調用方法 但是能解析C++方法。
<test.cpp 生成動態庫的源文件>
  1. #include <Akita/Akita.h>
  2. class TestLib{
  3. public:
  4. void display();
  5. void display(int a);
  6. };
  7. void TestLib::display() {
  8. cout<<"First display"<<endl;
  9. }
  10. void TestLib::display(int a) {
  11. cout<<"Second display"<<endl;
  12. }
  13. extern "C" {
  14. TestLib obj;
  15. void display() {
  16. obj.display();
  17. }
  18. void display_int() {
  19. obj.display(2);
  20. }
  21. }
g++ test.cpp -fPIC -shared -o libtest.so
使用這種方法有點麻煩 但是可以解決問題。注意到後面還是會有個extern "C" 不然構建後的動態鏈接庫沒有這些函數的符號表的。

<call.py 調用動態庫的源文件>

  1. import ctypes
  2. so = ctypes.CDLL("./libtest.so")
  3. so.display()
  4. so.display_int(1)
運行結果如下:
  1. ^[root@:~/Projects/nugget/kvDB-py]#python call.py
  2. First display
  3. Second display
C/C++調用Python模塊

<test.cpp >

  1. #include <Akita/Akita.h>
  2. #include <Python.h>
  3. int main() {
  4. Py_Initialize();
  5. if (!Py_IsInitialized()) return FALSE;
  6. PyRun_SimpleString("import sys");
  7. PyRun_SimpleString("sys.path.append('./')");
  8. //import Module
  9. PyObject* pModule = PyImport_ImportModule("hello");
  10. if (!pModule) {
  11. cout<<"Can't import Module!/n"<<endl;
  12. return -1;
  13. }
  14. PyObject* pDict = PyModule_GetDict(pModule);
  15. if (!pDict) {
  16. return -1;
  17. }
  18. //fetch Function
  19. PyObject* pFunHi = PyDict_GetItemString(pDict, "display");
  20. PyObject_CallFunction(pFunHi, "s", "Crazybaby");
  21. Py_DECREF(pFunHi);
  22. //Release
  23. Py_DECREF(pModule);
  24. Py_Finalize();
  25. return 0;
  26. }
#g++ test.cpp -I/usr/local/include/python2.7 -ldl -lutil -lpthread -lpython2.7


<call.py>

  1. def display(name):
  2. print "hi",name

---------

C++為Python編寫擴展模塊
Python為C++提供腳本接口。

有了兩者交互 方便之極。

Copyright © Linux教程網 All Rights Reserved