【问题标题】:python ctype initialising a structurepython ctype初始化一个结构
【发布时间】:2013-12-27 10:46:08
【问题描述】:

我的结构包含所有 unsigned char 元素

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;

下面的函数调用结构体

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

我将此结构转换为 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')

然后我加载了dll文件

hllDll.WriteCANMessage(handle, pmsg)

但这会出错

错误:0x00000000 处的访问冲突

【问题讨论】:

    标签: python windows ctypes


    【解决方案1】:

    您按值传递了pmsg,但该函数需要一个指针。由于您已初始化为全零,因此该函数最终会取消引用 NULL 指针。然后 ctypes 使用 Windows SEH 将访问冲突路由到 Python 异常。

    您需要使用byref(pmsg) 来传递引用。此外,定义函数的 argtypes 以确保在 64 位系统上正确处理指针。

    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))
    

    【讨论】:

    • 但是这个方法关闭python程序说python.exe遇到问题需要关闭
    • 这是一个新问题。您必须为问题添加更多上下文。
    • 对不起,我错过了一点,现在只发现 unsigned char *plBuf = (unsigned char *)&pmsg;我怎样才能包含这个?
    • 我不明白你的意思。请更新您的问题,详细说明您正在尝试做什么。
    • 如何为这个表达式添加 python ctype unsigned char *plBuf = (unsigned char *)&pmsg;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 2013-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多