问题描述
我遇到其中来自母体结构数据被正确编组的问题,而是在子结构中的数据是没有的。在C中的结构定义和功能:
I am running into an issue where data from the parent struct is correctly marshalled, but the data in the child struct is not. The struct definitions and functions in 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 code:
The C# P/Invoke code:
[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);
当我把code使用方法:
When I put the code to use:
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
正确整理(如乔
和蠢货
),然而 contact.cell
和 contact.home
都没有。在 contact.cell
通常是一些垃圾和 contact.home
是什么。
The human.first
and human.last
are marshalled correctly (e.g. "Joe"
and "Schmoe"
), however the contact.cell
and contact.home
are not. The contact.cell
is usually some garbage and contact.home
is nothing.
我依然pretty新编组。我不能编组是否正确?为什么结构contact_info *联系人
数据未正确设置?
I am still pretty new to marshalling. Am I not marshalling correctly? Why is the struct contact_info *contact
data not being set correctly?
有关完整的源看到这个。
For full source see this GitHub gist.
推荐答案
您正在转换human.contact您调用结构之前import_csv,所以它会包含任何东西保留在内存中,当你没有分配它。
Your are converting human.contact to your structure before calling import_csv, so it will contain anything left in memory when you did allocate it.
如果您将在其中创建您的来电下面接触import_csv它应该有正确的数据就行了。
If you move the line where you create contact below your call to import_csv it should have the right data.
这篇关于编组C#和C之间的嵌套结构 - 简单的HelloWorld的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!