封送C#和C-Simple HelloWorld之间的嵌套结构

本文关键字:嵌套 结构 之间 HelloWorld C-Simple 封送 | 更新日期: 2023-09-27 18:00:02

我遇到一个问题,父结构中的数据被正确整理,但子结构中的信息却没有。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);

C#p/Invoke代码:

[StructLayout(LayoutKind.Sequential)]
public struct contact_info
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)]
    public String cell;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)]
    public String home;
}
[StructLayout(LayoutKind.Sequential)]
public struct human
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)]
    public String first;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)]
    public String 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)]String path, ref human person);

当我使用代码时:

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);

human.firsthuman.last被正确编组(例如"Joe""Schmoe"),但是contact.cellcontact.home不是。contact.cell通常是一些垃圾,而contact.home什么都不是。

我对编组还很陌生。我的编组是否不正确?为什么struct contact_info *contact数据设置不正确?

有关完整的源代码,请参阅GitHub要点。

封送C#和C-Simple HelloWorld之间的嵌套结构

在调用import_csv之前,您正在将human.contact转换为您的结构,因此当您分配它时,它将包含内存中剩下的任何内容。

如果将创建联系人的行移到import_csv的调用下方,它应该具有正确的数据。