gpt4 book ai didi

c# - 在 C# 和 C 之间编码嵌套结构 - 简单的 HelloWorld

转载 作者:行者123 更新时间:2023-11-30 15:34:25 26 4
gpt4 key购买 nike

我遇到了一个问题,父结构中的数据已正确编码,但子结构中的数据未正确编码。 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.first human.last 已正确编码(例如 “Joe”“Schmoe”),但是 contact.cellcontact.home 不是。 contact.cell 通常是一些垃圾,而 contact.home 什么也没有。

我对编码还很陌生。我编码不正确吗?为什么 struct contact_info *contact 数据设置不正确?

有关完整源代码,请参阅此 GitHub gist .

最佳答案

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

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

关于c# - 在 C# 和 C 之间编码嵌套结构 - 简单的 HelloWorld,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23296722/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com