2014-04-25 5 views
0

상위 구조체의 데이터가 올바르게 정렬되지만 하위 구조체의 데이터가 올바르지 않은 문제가 있습니다.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.firsthuman.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.cellcontact.home은 그렇지 않습니다. contact.cell은 보통 쓰레기이며 contact.home은 아무것도 아닙니다.

저는 마샬링에 꽤 익숙합니다. 나는 정확하게 마샬링하지 않습니까? struct contact_info *contact 데이터가 올바르게 설정되지 않은 이유는 무엇입니까?

전체 소스는 GitHub gist을 참조하십시오.

+0

'char'를'wchar_t'로 바꾸어보세요. 또는 마샬 러에게'char'을 사용하라고 말하세요 :'LPStr' BTW : MSDN 페이지를 읽었을뿐입니다. – Deduplicator

답변

1

import_csv를 호출하기 전에 human.contact를 구조체로 변환하고 있으므로 할당 한 메모리에 남아있는 내용이 모두 포함됩니다.

import_csv 호출 아래에서 연락처를 만드는 행을 이동하면 올바른 데이터가 있어야합니다.

+0

그 전화의 순서가 중요하다는 것을 깨닫지 못했습니다. 감사! –

+0

예, PtrToStructure가 포인터 주소를 가져 와서 구조체로 제공하기 때문에 중요합니다. 새 구조체를 만들고 포인터를 새로운 구조체에 복사합니다. – Gusman

관련 문제