Sto imparando Rust mentre cerco di trovare un'alternativa all'interop C# con C/C++.Come restituire un array di strutture da Rust a C#
Come è possibile scrivere il codice Rust come il codice C sotto? Questo è il mio codice Rust finora, senza la possibilità di marshall esso:
pub struct PackChar { id: u32, val_str: String, }
#[no_mangle]
pub extern fn get_packs_char(size: u32) -> Vec<PackChar> {
let mut out_vec = Vec::new();
for i in 0 .. size {
let int_0 = '0' as u32;
let last_char_val = int_0 + i % (126 - int_0);
let last_char = char::from_u32(last_char_val).unwrap();
let buffer = format!("abcdefgHi{}", last_char);
let pack_char = PackChar {
id: i,
val_str: buffer,
};
out_vec.push(pack_char);
}
out_vec
}
Il codice di cui sopra tenta di riprodurre il seguente codice C, che sono in grado di interoperare con così com'è.
void GetPacksChar(int size, PackChar** DpArrPnt)
{
int TmpStrSize = 10;
*DpArrPnt = (PackChar*)CoTaskMemAlloc(size * sizeof(PackChar));
PackChar* CurPackPnt = *DpArrPnt;
char dummyString[]= "abcdefgHij";
for (int i = 0; i < size; i++,CurPackPnt++)
{
dummyString[TmpStrSize-1] = '0' + i % (126 - '0');
CurPackPnt->IntVal = i;
CurPackPnt->buffer = strdup(dummyString);
}
}
Questo codice C potrebbe accedere tramite importazione DLL in C# come questo:
[Dllimport("DllPath", CallingConvention = CallingConvention.Cdecl)]
public static extern void GetPacksChar(uint length, PackChar** ArrayStructs)
PackChar* MyPacksChar;
GetPacksChar(10, &MyPacksChar);
PackChar* CurrentPack = MyPacksChar;
var contLst = new List<PackChar>();
for (uint i = 0; i < ArrL; i++, CurrentPack++)
contlist.Add(new PackChar() {
IntVal = CurrentPack->IntVal, buffer = contLst->buffer
});
Non conosco molto l'interoperabilità C#, ma una cosa è sempre vera per l'utilizzo di FFI con qualsiasi linguaggio esterno: non si devono usare tipi specifici di Ruggine come 'Vec' nelle funzioni 'extern'. Gli unici tipi di tipi che possono essere usati in tali funzioni sono tipi primitivi come interi, float e puntatori e strutture '# [repr (C)]' che consistono di questi tipi. –