PYTHON調(diào)用C++DLL的參數傳遞方法
1. PYTHON與(yǔ)C++參數變量的比較
2. 準備一個C++ DLL的測試工程文件,並編(biān)譯產生DLL文件,代(dài)碼如下:
C++文件(jiàn)(cpp):(注意在函數聲明上(shàng)加上extern "C" 的(de)修飾)
#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);
}
from ctypes import *
dll = cdll.LoadLibrary('DLL/dlltest.dll')
請注意:
1.如果不加任何修飾,默(mò)認傳入參數為int,傳出參數也為int
2.對於int以外的類型(如float),需要聲(shēng)明python函數的(de)傳入參(cān)數類型,傳出參數類型 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)
輸出(chū):2.5999999046325684
3.對於字符串char* ,在聲明傳入參數類型時,需要聲明(míng)為字符指針,然後分配一塊char數組,後(hòu)把這個數組強製(zhì)轉換(huàn)為(wéi)字符指針 並且,在把(bǎ)python腳本中(zhōng)的(de)數(shù)據結構(gòu)導入c++中時,需要把(bǎ)str轉換為bytes或者bytesarray類型,並且進行迭代器分解(jiě)
hello=dll.HelloWorld
hello.argtypes=[POINTER(c_char)] #傳(chuán)入參數(shù)為字符指針
STR=(c_char * 100)(*bytes("WiseGlove數據手套(tào)",'utf-8')) #把一組100個的字(zì)符定義為(wéi)STR
cast(STR, POINTER(c_char))
hello(STR)
輸出:WiseGlove數據手(shǒu)套
4.對於其他數據類型的數組,(例如int*),操(cāo)作相似(sì): Ints=dll.Ints
Ints.argtypes=[POINTER(c_int),c_int]
INT=(c_int * 100)(*[1,2,3]) #把列表傳入變長參數args*中
cast(INT, POINTER(c_int))
Ints(INT,c_int(3))
輸出:1 2 3
5.對於返回值為數組的情況,可(kě)以(yǐ)直(zhí)接使用索引去訪問,但是下標操作[]不是(shì)從迭代器中取對象,而是地址偏移: 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) # 如(rú)果不是C連續的內存,必須強製轉換
IMG = cast(a.ctypes.data, POINTER(c_int)) # 轉換為ctypes,這裏轉換後的可以直接利用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=' ')
怎麽樣, 小(xiǎo)夥伴們學會了Python語言調用C++dll的方(fāng)法了(le)嗎? 使(shǐ)用這個方法,可以調用WONGLOVE數據手套的sdk開發(fā)庫(kù)獲得數據手套的角度數據哦(ò)~~
- 上一篇:Unity3D實現碰撞檢測方法技巧好簡單哦 2019/11/1
- 下一篇:UNITY3D動畫模型的MESH COLLODER準確碰(pèng)撞檢 2019/8/8
