pythonctype,python ctype初始化结构

My structure contains all unsigned char elements

typedef struct

{

unsigned char bE;

unsigned char cH;

unsigned char cL;

unsigned char EId1;

unsigned char EId0;

unsigned char SId1;

unsigned char SId0;

unsigned char DLC;

unsigned char D0;

unsigned char D1;

unsigned char D2;

unsigned char D3;

unsigned char D4;

unsigned char D5;

unsigned char D6;

unsigned char D7;

} CMsg;

The below function calls the structure

extern int WriteCMessage(HANDLE hDev,CMsg* pMsg);

I converted this structure to python ctype

class CMsg(Structure):

_fields_ = [('bE', c_char),

('cH', c_char),

('cL', c_char),

('EId1', c_char),

('EId0', c_char),

('SId1', c_char),

('SId0', c_char),

('DLC', c_char),

('D0', c_char),

('D1', c_char),

('D2', c_char),

('D3', c_char),

('D4', c_char),

('D5', c_char),

('D6', c_char),

('D7', c_char)]

pmsg = CMsg('\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00')

Then i loaded the dll file

hllDll.WriteCANMessage(handle, pmsg)

But this gives error

Error: Access violation at 0x00000000

解决方案

You passed pmsg by value, but the function expects a pointer. Since you've initialized to all zeros, the function ends up dereferencing a NULL pointer. Then ctypes uses Windows SEH to route the access violation to a Python exception.

You need to use byref(pmsg) to pass a reference. Also, define the function's argtypes to ensure proper handling of the pointer on 64-bit systems.

from ctypes import *

from ctypes.wintypes import *

class CMsg(Structure):

_fields_ = [

('bE', c_ubyte),

('cH', c_ubyte),

('cL', c_ubyte),

('EId1', c_ubyte),

('EId0', c_ubyte),

('SId1', c_ubyte),

('SId0', c_ubyte),

('DLC', c_ubyte),

('D0', c_ubyte),

('D1', c_ubyte),

('D2', c_ubyte),

('D3', c_ubyte),

('D4', c_ubyte),

('D5', c_ubyte),

('D6', c_ubyte),

('D7', c_ubyte)]

hllDll = cdll...

hllDll.WriteCANMessage.argtypes = [HANDLE, POINTER(CMsg)]

handle = ...

pmsg = CMsg() # initially memset to {0}

hllDll.WriteCANMessage(handle, byref(pmsg))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值