You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用windows-rs时WM_COMMAND中获取Counter结构体触发对齐错误

问题分析与修复

核心问题

panic的根源是指针类型转换错误:

  • 通过Box::leak(Box::new(Counter{...}))得到的是*mut Counter类型指针,已存入GWLP_USERDATA。
  • 但increase_and_print函数中错误将取出的指针转换为*mut Box<Counter>,解引用时访问错误内存地址,触发对齐panic。

修复代码

修改increase_and_print中的指针转换逻辑:

fn increase_and_print(parent: HWND) {
    unsafe {
        let ptr = GetWindowLongPtrW(parent, GWLP_USERDATA);
        println!("GetWindowLongPtrW: {}", ptr);

        // 修正:转换为*mut Counter而非*mut Box<Counter>
        let ptr = ptr as *mut Counter;
        debug_assert!(!ptr.is_null());
        let c = &mut *ptr;
        c.counter += 1;
        println!("counter: {}", c.counter);
    }
}

额外内存安全建议

为避免内存泄漏,在WM_DESTROY消息中回收内存:

WM_DESTROY => {
    let ptr = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut Counter;
    if !ptr.is_null() {
        // 将指针重新包装为Box并自动释放
        Box::from_raw(ptr);
    }
    PostQuitMessage(0);
    LRESULT(0)
},

验证结果

修复后,点击按钮时计数器会正常自增到3,不再触发对齐panic。

内容的提问来源于stack exchange,提问作者chengbin du

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 04:46:28