How to manipulate Key-Value?

Hi,

I have a go program which uses the wasmer library to execute wasm bytecodes which are written in Rust.The bytecode depends on certain data that can be supplied only through the go program.
These state data is shared by the go program by writing it to the linear memory allocated by the wasmer library.
The rust logic is expected to read the data from the linear memory, unmarshal it and use it in its logic

Ex:
Using the rust code i'm allocating the data to a linear memory in go-wasmer environment and copying the byte array to a memory and get the pointer for that memory. Once the I get the pointer I'm again calling another function from rust say load_data which uses the generated pointer and should return the value associated with key (specified key). once I got the key, set that key back to gocode using cgo function, Then call some other function say getSI and use that key in its logic.
(Can think of these as setters and getters)

Now the real problem is, I'm not getting the way to read state variable from the pointer. I tried to unmarshal byte array (converted pointer to a byte array), but couldn't do that and unable to get value associated with the key.

My code looks like,

extern "C" {
    fn set_var(pointer: i32 );
    fn get_var()->i32;
}

#[no_mangle]
pub extern "C" fn load_data(R: *const i32) {
    let slice = unsafe { std::slice::from_raw_parts(R as *const u8, R as usize)};
    // code failing here
    let unmarshalled_value :HashMap<String,i32> = serde_json::from_slice(slice).unwrap();
    let data= unmarshalled_value.get("0xC_r");
    match data {
        Some(&x) => unsafe {set_var(x)},
        None => println!("unused data"),
    }
}

#[no_mangle]
pub extern "C" fn getSI(principal: u64, time: u64) -> f64 {
    principal as f64 * time as f64 * unsafe { get_var() } as f64 / 100.0
}

In this line, you use the value R as a pointer, then convert it to a number and use the same value as the length. This is definitely not correct:

let slice = unsafe { std::slice::from_raw_parts(R as *const u8, R as usize)};

If R points to a NUL-terminated string, you can use CStr to find its length:

let slice = unsafe { std::ffi::CStr::from_ptr(R as *const c_char).to_bytes() };

If the string is not NUL-terminated, then you'll need to pass the length explicitly as a separate argument.

@mbrubeck, yes, in the above code i mentioned same value for length. it supposed to be some other value. I tried passing integer value there.
But the real problem I'm facing is not on that line.

Once I have &[u8] I'm unable to deserialize it and get the value

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.