Je rencontre un problème dans lequel les données de la structure parente sont correctement organisées, mais pas celles de la structure enfant. Les définitions et fonctions de structure en C:
struct contact_info { char cell[32]; char home[32]; }; struct human { char first[32]; char last[32]; struct contact_info *contact; }; __declspec(dllexport) int __cdecl say_hello(struct human *person); __declspec(dllexport) int __cdecl import_csv(char *csvPath, struct human *person);
Le code C # P / Invoke:
[StructLayout(LayoutKind.Sequential)] public struct contact_info { [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public Ssortingng cell; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public Ssortingng home; } [StructLayout(LayoutKind.Sequential)] public struct human { [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public Ssortingng first; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public Ssortingng last; public IntPtr contact; } [DllImport("HelloLibrary.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int say_hello(ref human person); [DllImport("HelloLibrary.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int import_csv([MarshalAs(UnmanagedType.LPStr)]Ssortingng path, ref human person);
Quand je mets le code à utiliser:
HelloLibrary.human human = new HelloLibrary.human(); human.contact = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(HelloLibrary.contact_info))); HelloLibrary.contact_info contact = (HelloLibrary.contact_info) Marshal.PtrToStructure(human.contact, typeof(HelloLibrary.contact_info)); HelloLibrary.import_csv(args[0], ref human); Console.WriteLine("first:'{0}'", human.first); Console.WriteLine("last:'{0}'", human.last); Console.WriteLine("cell:'{0}'", contact.cell); Console.WriteLine("home:'{0}'", contact.home);
Les human.first
et human.last
sont correctement organisés (par exemple, "Joe"
et "Schmoe"
), mais pas le contact.cell
ni le contact.home
. Le contact.cell
est généralement une poubelle et contact.home
n’est rien.
Je suis encore assez nouveau pour le marshalling. Est-ce que je ne m’organise pas correctement Pourquoi les données de struct contact_info *contact
ne sont-elles pas correctement définies?
Pour la source complète, voir cet article de GitHub .
Vous convertissez human.contact dans votre structure avant d’appeler import_csv. Par conséquent, il contiendra tout ce qui rest en mémoire lorsque vous l’avez alloué.
Si vous déplacez la ligne où vous créez un contact au-dessous de votre appel à import_csv, il devrait contenir les bonnes données.