(1)手動轉化:
當需要定義為unsigned的數(shù)據(jù)時(有符號轉到無符號):
如果unsigned short是16位,value & 0xffff
如果unsigned long是32位,value & 0xffffffff
如果unsigned long是64位,value & 0xffffffffffffffff
請注意,雖然這給了你在C中的值,它仍然是一個有符號的值,因此任何后續(xù)計算都可能給出否定結果,
(2)利用ctypes 包
Python 調(diào)用 C 動態(tài)鏈接庫,包括結構體參數(shù)、回調(diào)函數(shù)
第一步:ctypes 包準備
使用 ctypes,需要首先安裝 python-dev 包;
第二步:so 文件準備
將你的 C 代碼編譯成 .so 文件
第三步:
from ctypes import *
so_file = cdll.LoadLibrary('./libtest.so') # 如果前文使用的是 import ctypes,則這里應該是
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)
]