Код: Выделить всё
#[no_mangle]
pub extern "C" fn get_bytes(len: &mut i32, bytes: *mut *mut u8) {
let mut buf : Vec = get_data();
buf.shrink_to_fit();
// Set the output values
*len = buf.len() as i32;
unsafe {
*bytes = buf.as_mut_ptr();
}
std::mem::forget(buf);
}
< /code>
Из C#я могу позвонить ему без сбоя. (Вместо аварии я предполагаю, что это правильно, но не уверен на 100%):
[DllImport("my_lib")] static extern void get_bytes(ref int len,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] ref byte[] bytes);
void test()
{
int len = 0;
byte[] bytes = null;
get_bytes(ref len, ref bytes);
}
Код: Выделить всё
#[no_mangle]
pub extern "C" fn free_bytes(len: i32, bytes: *mut *mut u8) {
// also tried with: -------------- bytes: *mut u8
assert!(len > 0);
// Rebuild the vec
let v = unsafe { Vec::from_raw_parts(bytes, len as usize, len as usize) };
//println!("bytes to free: {:?}", v);
drop(v); // or it could be implicitly dropped
}
< /code>
и соответствующий C#. Создание вызова сбоя моего приложения: < /p>
[DllImport("my_lib")] extern void free_bytes(int len, ref byte[] bytes);
void test()
{
int len = 0;
byte[] bytes = null;
get_bytes(ref len, ref bytes);
// copy bytes to managed memory
bytes[] copy = new byte[len];
bytes.CopyTo(copy, 0);
// free the unmanaged memory
free_bytes(len, ref bytes); // crash occurs when executing this function
}
Код: Выделить всё
capacity
Подробнее здесь: https://stackoverflow.com/questions/667 ... ed-in-rust