(1)手動轉(zhuǎn)化:
當需要定義為unsigned的數(shù)據(jù)時(有符號轉(zhuǎn)到無符號):
如果unsigned short是16位柄延,value & 0xffff
如果unsigned long是32位秆乳,value & 0xffffffff
如果unsigned long是64位阻逮,value & 0xffffffffffffffff
請注意,雖然這給了你在C中的值,它仍然是一個有符號的值,因此任何后續(xù)計算都可能給出否定結(jié)果,
(2)利用ctypes 包
Python 調(diào)用 C 動態(tài)鏈接庫,包括結(jié)構(gòu)體參數(shù)娩梨、回調(diào)函數(shù)
第一步:ctypes 包準備
使用 ctypes沿腰,需要首先安裝 python-dev 包;
第二步:so 文件準備
將你的 C 代碼編譯成 .so 文件
第三步:
from ctypes import *
so_file = cdll.LoadLibrary('./libtest.so') # 如果前文使用的是 import ctypes狈定,則這里應(yīng)該是
print('so_file class:', type(so_file))
C 代碼
typedef struct _test_struct
{
int integer;
char * c_str;
void * ptr;
int array[8];
} TestStruct_st;
'TestStruct_st 的 Python 版本'
from ctypes import *
INTARRAY8 = c_int * 8
class PyTestStruct(Structure):
_fields_ = [
("integer", c_int),
("c_str", c_char_p),
("ptr", c_void_p),
("array", INTARRAY8)
]