• PYTHON調用C++DLL的參數傳(chuán)遞方法(fǎ)

    2019/9/16      點擊:

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

    2. 準備一個C++ DLL的測試工程(chéng)文(wén)件,並(bìng)編譯產生DLL文件,代碼如(rú)下:
    C++文件(cpp):(注意在函數(shù)聲明上加上(shàng)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')
    請注(zhù)意:


    1.如果不加任何修(xiū)飾,默認傳入參數為int,傳出參(cān)數也為int 

    2.對於int以外的(de)類型(如float),需要聲明python函數的傳入參數類型,傳出參數類型(xíng) fun.argtypes=[c_float,c_float]  #定義傳參類型
     fun.restype=c_float             #定義返(fǎn)回值類型(xíng)
     a=fun(c_float(1.4),c_float(1.2))
     print(type(a))
     print(a)
     輸出:2.5999999046325684 

    3.對於(yú)字符串char* ,在聲明傳入參數類型時,需要聲明為字符指針,然後分配(pèi)一(yī)塊char數組,後把這個數組(zǔ)強製轉(zhuǎn)換為字符指針 並(bìng)且,在把python腳本中的(de)數據結構導(dǎo)入c++中時,需要把str轉換為bytes或者bytesarray類(lèi)型,並且進(jìn)行迭代(dài)器分解
     hello=dll.HelloWorld
     hello.argtypes=[POINTER(c_char)]    #傳入參數(shù)為字符指針
     STR=(c_char * 100)(*bytes("WiseGlove數據手(shǒu)套",'utf-8')) #把一組100個的(de)字符定義為STR
     cast(STR, POINTER(c_char))
     hello(STR)
     輸出:WiseGlove數據手套 

    4.對於其他數據類型的數組(zǔ),(例如int*),操(cāo)作相似: Ints=dll.Ints
     Ints.argtypes=[POINTER(c_int),c_int]
     INT=(c_int * 100)(*[1,2,3]) #把列表傳(chuán)入變長參數args*中
     cast(INT, POINTER(c_int))
     Ints(INT,c_int(3))
     輸出:1 2 3  

    5.對於返回值為數(shù)組的(de)情況,可以直接使用索引去訪問,但是下標操作[]不是從(cóng)迭代器中(zhōng)取對象,而是地(dì)址偏移: 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)  # 如果不(bú)是C連續(xù)的內存,必須強製轉換
         IMG = cast(a.ctypes.data, POINTER(c_int))  # 轉換為(wéi)ctypes,這裏轉換後的可以直接(jiē)利用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é)會(huì)了Python語言調用C++dll的方法(fǎ)了嗎? 使用這個方法,可以調(diào)用WONGLOVE數(shù)據手套的sdk開發庫獲得數據手套的角(jiǎo)度數據哦~~



    网站地图 正能量网-传播正能量弘扬主旋律-免费正能量网站www正能量-免费正能量网站www正能量下载在线观看官网