상위 구조체의 데이터가 올바르게 정렬되지만 하위 구조체의 데이터가 올바르지 않은 문제가 있습니다.C#과 C 사이에 중첩 된 구조체를 마샬링 - 간단한 HelloWorld
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
가 정렬 화되어 내가 사용하는 코드를 삽입 할 때
[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);
: 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는/코드를 호출 올바르게 입력하십시오 (예 : "Joe"
및 "Schmoe"
). 그러나 contact.cell
및 contact.home
은 그렇지 않습니다. contact.cell
은 보통 쓰레기이며 contact.home
은 아무것도 아닙니다.
저는 마샬링에 꽤 익숙합니다. 나는 정확하게 마샬링하지 않습니까? struct contact_info *contact
데이터가 올바르게 설정되지 않은 이유는 무엇입니까?
전체 소스는 GitHub gist을 참조하십시오.
'char'를'wchar_t'로 바꾸어보세요. 또는 마샬 러에게'char'을 사용하라고 말하세요 :'LPStr' BTW : MSDN 페이지를 읽었을뿐입니다. – Deduplicator