Python調用C/C++初步

原文地址:http://daweibalong.iteye.com/blog/1660181
測試庫要求做到全部自動化–動態添加新的計算圖像指標可以直接不用重寫底層java程序……這段時間在學Python,由於Python的ctypes可以試python輕鬆調用動態鏈接庫,從而調用c/c++程序,於是想到可以在添加指標的時候有管理員再上傳相關方法的dll或so文件,由Python進行調用新的指標計算方法進行重新計算。不知效果如何,先測試簡單的調用:
1、編寫test.c

    #include <stdlib.h>  

    int foo(int a, int b)  
    {  
        printf("Your input %i and %i\n", a, b);  
        return a + b;  
    }  

2、 gcc編譯:gcc -o test.so -shared -fPIC test.c
3、 編寫test.py

    import ctypes  
    ll = ctypes.cdll.LoadLibrary 
    lib = ll("./test.so")  
    lib.foo(1, 3)  

4、運行
python test.py
成功運行 Python調用C/C++初步

不過在調用c++文件的時候會發生錯誤,具體原因不詳,但依然可以調用!!!:
1、編寫c++文件test2.cpp
Cpp代碼 收藏代碼

    #include<iostream>  
    using namespace std;  
    void foo2(int a,int b)  
    {  
        cout<<a<<" "<<b<<endl;  
    }  

//以下爲必須
Cpp代碼 收藏代碼

    extern "c"  
    {  
        void cfoo2(int a,int b)  
        {  
            foo2(a,b);  
        }  
    }  

2、編譯c++文件:
g++ -o test2.so -shared -fPIC test2.c
3、 編寫test2.py

    import ctypes  
    ll = ctypes.cdll.LoadLibrary 
    lib = ll("./test2.so")  
    lib.cfoo2(1, 3)
  ```    

4、運行:
python test2.py
成功!

問題補充:
1、在windows下調用dll,如果過python是64位,那麼在寫dll時編譯要用x64,要不然會出現錯誤的win32提示。
2、在h文件中:
Cpp代碼    收藏代碼
extern "C" int __declspec(dllexport)add(int x,int y);  

cpp:
Cpp代碼    收藏代碼
int __declspec(dllexport)add(int x,int y)  
{  
    cout<<x<<" "<<y<<endl;  
    return x+y;  
}  

“`

發佈了19 篇原創文章 · 獲贊 9 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章