0

I use python cffi to call rust code.

rust code


#[no_mangle]
pub extern "C" fn fixU32_decode(raw: *const libc::c_char) -> *mut u32 {
    let str_raw = unsafe { CStr::from_ptr(raw) }.to_str().unwrap().to_string();
    let bytes_raw = hex::decode(str_raw).unwrap();
    let mut u8_fixed: [u32; 6] = Decode::decode(&mut &bytes_raw[..]).unwrap();
    println!("fixU32_decode input {:?}",u8_fixed);
    let ptr = u8_fixed.as_mut_ptr();
    std::mem::forget(u8_fixed);
    ptr
}

Python

ffi = FFI()
ffi.cdef("""
unsigned int* fixU32_decode(char* raw);
""")
s1 = ffi.fixU32_decode("010000000200000003000000040000000500000006000000")
print(s1) # <cdata 'unsigned int *' 0x16b36629c>? 

Add how to get return array from python use cffi

hahaming
  • 43
  • 4
  • Where is the returned array? Did you paste fixU32 "encode" instead of "decode" that you call from Python? – matejcik Aug 01 '22 at 15:23
  • @matejcik sorry, my fault, i updated the rust code – hahaming Aug 02 '22 at 00:06
  • 2
    See https://stackoverflow.com/questions/68854193/using-an-int-array-return-value-in-python-via-cffi – Unlikus Aug 02 '22 at 09:28
  • @Unlikus Thank you for your answer, Can you help with this problem? – hahaming Aug 07 '22 at 13:58
  • 1
    @hahaming the linked answer tells you that you can use your obtained pointer in python just as in C by indexing it, for Rust this is the same thing. you can access s1[0], s1[1] and so on. There is no rangechecking. – Unlikus Aug 08 '22 at 13:36
  • @Unlikus Can you help with this issue [ffi-napi](https://stackoverflow.com/questions/73234661/how-to-get-ffi-array-from-node-ffi-napi)? – hahaming Aug 09 '22 at 06:28

0 Answers0