Trying to make a chunk of pointer manipulation code into a function or macro

⚓ Rust    📅 2025-11-07    👤 surdeus    👁️ 7      

surdeus

I have a reference to an enum instance. I need to get the address of the payload inside it and 'return' it as a *c_void

the enum

pub enum ArgVal {
    Pointer(*mut c_void),
    U64(u64),
    F64(f64),
    I64(i64),
    I32(i32),
    U32(u32),
    I16(i16),
    U16(u16),
    F32(f32),
    Char(u8),
}

The code that I have to do it inline

// set up the enum
        func.arg_vals.push(ArgVal::Pointer(p));
// get its address
        let penum = &func.arg_vals[func.arg_vals.len() - 1];

// this code needs to be factored out
        let pval = if let ArgVal::Pointer(ref val) = penum {
            val
        } else {
            panic!("Expected Pointer ArgVal")
        };
        unsafe { mem::transmute::<&*mut c_void, *mut c_void>(pval) }

note that the code is different depending on the enum type, here is one for a u64 payload

        func.arg_vals.push(ArgVal::U64(*self));
        let penum = &func.arg_vals[func.arg_vals.len() - 1];
        let pval = if let ArgVal::U64(ref val) = penum {
            val
        } else {
            panic!("Expected u64 ArgVal")
        };
        unsafe { mem::transmute::<&u64, *mut c_void>(pval) }

I need to change the enum variant that I match and the src type in the transmute call.
(there may be different ways of obtaining the same result, please advise if so)

I can obviously just copy / paste / tweak but it would be nice if I could make a macro or function because i need it all over the place

3 posts - 2 participants

Read full topic

🏷️ Rust_feed