< 返回版块

WingOwO 发表于 2021-03-22 17:02

Tags:闭包,C回调,Windows API

声明了一个闭包

        let mut closure  = |code : i32, w_param : usize, l_param : isize| -> isize {
            let pKB = l_param as LPKBDLLHOOKSTRUCT;
            //let bKeyToShield : bool  = false;
            if code == HC_ACTION
            {
                match w_param as u32
                {
                    WM_KEYDOWN => 
                    {
                        
                        if (*pKB).vkCode == 0x0D as u32
                        {
                            println!("ESCAPE");
                        }
                    }
                    WM_KEYUP =>
                    {
        
                    }
                    _ => {}
                }
            }
            return 0;
        };

然后通过多重包装使他转为unsafe extern "system" fn (i32, usize, isize) -> isize

let mut trait_obj: &mut FnMut(i32, usize, isize) -> isize = &mut closure;
let trait_obj_ref = &mut trait_obj;
let closure_pointer_pointer = trait_obj_ref as *mut _ as *mut unsafe extern "system" fn (i32, usize, isize) -> isize;

编译并无任何问题,但是一旦调用其方法就是异常退出,请问有什么好的解决方法吗? 参考过stackoverflow的连接


Ext Link: https://stackoverflow.com/questions/38995701/how-do-i-pass-a-closure-through-raw-pointers-as-an-argument-to-a-c-function

评论区

写评论
ywxt 2021-03-23 18:06
let trait_obj_ref: &mut &mut dyn FnMut(i32) -> bool = unsafe {
        let closure_pointer_pointer = lparam as *mut c_void;
        &mut *(closure_pointer_pointer as *mut _)
    };

把函数指针先转换成闭包再调用。

作者 WingOwO 2021-03-23 13:58

那请问有转换的方法吗?

--
👇
tcz717: Fn 闭包是宽指针不能直接转换为函数指针

tcz717 2021-03-23 09:12

Fn 闭包是宽指针不能直接转换为函数指针

1 共 3 条评论, 1 页