2011-10-20 59 views
3

我將'unmanaged c'代碼封送到下面給出的C#代碼中。如何在c#中訪問編組結構數據的編組指針?

[DllImport("ContainerDll.dll", CallingConvention = CallingConvention.Cdecl)] 
    public static extern IntPtr NodeSearch(IntPtr firstNode, string key); 

    IntPtr firstNode = IntPtr.Zero; 

    private void button4_Click(object sender, EventArgs e) 
    { 
     IntPtr ret = NodeSearch(firstNode, "key_string"); 
    } 

    //NodeSearch method will be called which is present in 'ContainerDll.dll' 
    //pointer to structure will be returned. 

    //my c-structure contains these fields. 

    //  typedef struct container 
    //  { 
    //    char Name[20]; 
    //    void *VoidData; 
    //    struct container *Link; 
    //  }  
    //    Node; 

現在,我的C#類型'IntPtr'類型的變量'ret'獲得了這個結構的指針。它具有從'NodeSearch'方法返回的地址。

如何在C#表單應用程序(也在控制檯應用程序中)訪問?

我想我不能這樣使用:ret->名稱[0],ret-> VoidData等

我是初學者!你可以請我嗎?

+0

這個http://blogs.msdn.com/b/jaredpar/archive/2008/11/05/dereference-a-double-intptr.aspx – Adam

+0

感謝您的答覆。這對我很有用。 – SHRI

回答

3

您將需要在C#中創建一個兼容的struct定義,並使用Marshal類來封送指向該結構的指針。

結構定義看起來像下面這樣:

[StructLayout(LayoutKind.Sequential)] 
struct Container 
{ 
    [MarshalAs(UnmanagedType.ByValTStr, CharSet = CharSet.Ansi, SizeConst = 20)] 
    string Name; 
    IntPtr VoidData; 
    IntPtr Link 
} 

然後,您應該能夠當元帥的指針,這個結構類似如下的方式:

var ret = NodeSearch(IntPtr.Zero, "key_string"); 
var retContainer = (Container)Marshal.PtrToStructure(ret, typeof(Container)); 

爲了檢索鏈接或無效數據,您還需要致電Marshal.PtrToStructure

+0

感謝分配的詳細回覆。我會通過這個並回到你身邊。這是我在堆棧溢出中的第一個問題。謝謝。 – SHRI