我有以下包含可变C风格字符串的C结构。
typedef struct XMLCFG_PARAMS {
unsigned long ulMedia; // Save/load to file or buffer
unsigned long ulCfgFlags; // Flags say what type of info to save/load
char* pszBufOrFilename; // The buffer or the filename
unsigned long ulBufLen; // How long is the buffer (in bytes)
} XMLCFG_PARAMS;
我已经在Python中定义了这样的结构:
class XMLCFG_PARAMS(ctypes.Structure):
_fields_ = [
("ulMedia", ctypes.c_ulong),
("ulCfgFlags", ctypes.c_ulong),
("pszBufOrFilename", ctypes.c_char_p),
("ulBufLen", ctypes.c_ulong),
]
然后实例化此结构:
xml_cfg = XMLCFG_PARAMS()
xml_cfg.ulMedia = XMLCFG_BUFFER
xml_cfg.ulCfgFlags = config_flags
xml_buffer = ctypes.create_string_buffer(xml_text, size=1024 * 1024)
xml_cfg.pszBufOrFilename = ctypes.c_char_p(ctypes.addressof(xml_buffer))
xml_cfg.ulBufLen = len(xml_buffer)
C调用返回错误WindowsError: exception: access violation reading 0x6E6F697B
。
我怀疑我在实例化XMLCFG_PARAMS
结构,特别是pszBufOrFilename
字段的方式上做错了,因为这是我第一次遇到可变的C风格结构中的字符串。
BOOL Control(unsigned long ulEngId,
unsigned long cmd_id,
unsigned long *ulParam0 = 0,
unsigned long *ulParam1 = 0,
unsigned long *ulParam2 = 0,
unsigned long *ulParam3 = 0);
dll_handle.Control(engine_id, cmd_id, ctypes.pointer(xml_cfg), None, None, None)
hex(ctypes.addressof(xml_buffer))
的输出为0x3940020
,而异常持续引用0x6E6F697B
。这是在Win XP上,所以我猜这个内存地址不会改变,因为操作系统缺少ASLR。