• PYTHON調(diào)用C++DLL的參數(shù)傳遞方法

    2019/9/16??????點擊:

    1. PYTHON與C++參數(shù)變量的比較

    2. 準(zhǔn)備一個C++ DLL的測試工程文件,并編譯產(chǎn)生DLL文件,代碼如下:
    C++文件(cpp):(注意在函數(shù)聲明上加上extern "C" 的修飾)

    #include “testdll.h”
    extern "C" {
        __declspec(dllexport) int Double(int x);
        __declspec(dllexport) float floatAdd(float a,float b); 
        __declspec(dllexport) void HelloWorld(char * str); 
        __declspec(dllexport) void Ints(int * arr,int n); 
    }
    int Double(int x){
        return x*2;
    }
    float floatAdd(float a,float b) {
        return a+b;
    }
    void HelloWorld(char * str){
        puts(str);
    }

    在python腳本中使用ctypes加載dll :
     from ctypes import *
     dll = cdll.LoadLibrary('DLL/dlltest.dll')
    請注意:


    1.如果不加任何修飾,默認(rèn)傳入?yún)?shù)為int,傳出參數(shù)也為int 

    2.對于int以外的類型(如float),需要聲明python函數(shù)的傳入?yún)?shù)類型,傳出參數(shù)類型 fun.argtypes=[c_float,c_float]  #定義傳參類型
     fun.restype=c_float             #定義返回值類型
     a=fun(c_float(1.4),c_float(1.2))
     print(type(a))
     print(a)
     輸出:2.5999999046325684 

    3.對于字符串char* ,在聲明傳入?yún)?shù)類型時,需要聲明為字符指針,然后分配一塊char數(shù)組,后把這個數(shù)組強制轉(zhuǎn)換為字符指針 并且,在把python腳本中的數(shù)據(jù)結(jié)構(gòu)導(dǎo)入c++中時,需要把str轉(zhuǎn)換為bytes或者bytesarray類型,并且進行迭代器分解
     hello=dll.HelloWorld
     hello.argtypes=[POINTER(c_char)]    #傳入?yún)?shù)為字符指針
     STR=(c_char * 100)(*bytes("WiseGlove數(shù)據(jù)手套",'utf-8')) #把一組100個的字符定義為STR
     cast(STR, POINTER(c_char))
     hello(STR)
     輸出:WiseGlove數(shù)據(jù)手套 

    4.對于其他數(shù)據(jù)類型的數(shù)組,(例如int*),操作相似: Ints=dll.Ints
     Ints.argtypes=[POINTER(c_int),c_int]
     INT=(c_int * 100)(*[1,2,3]) #把列表傳入變長參數(shù)args*中
     cast(INT, POINTER(c_int))
     Ints(INT,c_int(3))
     輸出:1 2 3  

    5.對于返回值為數(shù)組的情況,可以直接使用索引去訪問,但是下標(biāo)操作[]不是從迭代器中取對象,而是地址偏移: def fillHoleCpp(im):
         dll = cdll.LoadLibrary("bfs.dll")
         bfs=dll.bfs
         bfs.argtypes = [POINTER(c_int),c_int]
         bfs.restype = POINTER(c_int)
         a = np.asarray(range(16), dtype=np.int32).reshape([4, 4])
         if not a.flags['C_CONTIGUOUS']:
             a = np.ascontiguous(a, dtype=a.dtype)  # 如果不是C連續(xù)的內(nèi)存,必須強制轉(zhuǎn)換
         IMG = cast(a.ctypes.data, POINTER(c_int))  # 轉(zhuǎn)換為ctypes,這里轉(zhuǎn)換后的可以直接利用cty
         cast(IMG, POINTER(c_int))
         length=a.size
         ans=bfs(IMG,c_int(length))
         print(type(ans))
         for i in range(0,length):
             print(ans[i],end=' ')
    怎么樣, 小伙伴們學(xué)會了Python語言調(diào)用C++dll的方法了嗎? 使用這個方法,可以調(diào)用wiseglove數(shù)據(jù)手套的sdk開發(fā)庫獲得數(shù)據(jù)手套的角度數(shù)據(jù)哦~~