Exemple de signature de l’API C:
void Func(unsigned char* bytes);
En C, quand je veux passer un pointeur sur un tableau, je peux faire:
unsigned char* bytes = new unsigned char[1000]; Func(bytes); // call
Comment traduire les API ci-dessus en P / Invoke de manière à pouvoir passer un pointeur sur un tableau d’octets C #?
Le moyen le plus simple de passer un tableau d’octets consiste à déclarer le paramètre dans votre instruction d’importation en tant que tableau d’octets.
[DllImport EntryPoint="func" CharSet=CharSet.Auto, SetLastError=true] public extern static void Func(byte[]); byte[] ar = new byte[1000]; Func(ar);
Vous devez également pouvoir déclarer le paramètre en tant que IntPtr et marshaler les données manuellement.
[DllImport EntryPoint="func" CharSet=CharSet.Auto, SetLastError=true] public extern static void Func(IntPtr p); byte[] ar = new byte[1000]; IntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)) * ar.Length); Marshal.Copy(ar, 0, p, ar.Length); Func(p); Marshal.FreeHGlobal(p);
Vous pouvez utiliser un code non sécurisé:
unsafe { fixed(byte* pByte = byteArray) IntPtr intPtr = new IntPtr((void *) pByte); Func(intPtr); }
Si vous devez utiliser un code sécurisé, vous pouvez utiliser quelques astuces:
IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf(byteArray)); Marshal.Copy(byteArray, 0, intPtr, Marshal.SizeOf(byteArray)); Func(intPtr); Marshal.FreeHGlobal(intPtr);
Cependant, le code de sécurité va être lent IMHO.
Voici la signature appropriée pour la fonction native.
[System.Runtime.InteropServices.DllImportAtsortingbute("", EntryPoint="Func")] public static extern void Func(System.IntPtr bytes) ;