2013-06-19 57 views
0

我有一個問題,我無法在網上找到答案。 我想從我的C#代碼中調用一個C++函數。 C++函數聲明爲:如何將包含void *的結構從C++傳遞到c#?

int read(InfoStruct *pInfo, int size, BOOL flag) 

結構如下

typedef struct 
{ 
    int ID; 
    char Name[20]; 
    double value; 
    void *Pointer; 
    int time; 
}InfoStruct; 

在我的C#代碼,我寫道:

public unsafe struct InfoStruct 
{ 
    public Int32 ID; 
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)] 
    public string Name; 
    public Double value; 
    public void *Pointer; 
    public Int32 time; 
    }; 

[DllImport("mydll.dll", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)] 
     public static extern unsafe int read(out MeasurementInfoStruct[] pInfo, int size, bool flag); 

我試圖運行的代碼,但它崩潰所以我想我對這個結構特別是void *犯了一個錯誤,但是我無法弄清楚需要改變什麼。也可能是這個函數返回一個結構數組,也許我沒有把它調用正確。 你能幫我解決嗎? 非常感謝。

+3

您是否嘗試過的IntPtr? –

+0

你必須編組每個C#中的類變量,並嘗試在C#中使用引用而不是intptr。如果可能的話,會盡力爲您解決問題併發布解決方案。 – 2013-06-19 10:23:24

+0

我嘗試IntPtr沒有成功。 – diditexas

回答

0

我創建了一個測試應用程序和代碼如下,它是工作的罰款...

// CPP code 

typedef struct 
{ 
    int ID; 
    char Name[20]; 
    double value; 
    void *Pointer; 
    int time; 
}InfoStruct; 

int WINAPI ModifyListOfControls(InfoStruct *pInfo, int size, bool flag) 
{ 

    int temp = 10; 
    pInfo->ID = 10; 
    strcpy(pInfo->Name,"Hi"); 
    pInfo->value = 20.23; 
    pInfo->Pointer = (void *)&temp; 
    pInfo->time = 50; 
    return 0; 
} 
/***************************************************/ 
// This is C# code 
[StructLayout(LayoutKind.Sequential)] 
public struct InfoStruct 
{ 
    public Int32 ID; 
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)] 
    public string Name; 
    public Double value; 
    public IntPtr Pointer; 
    public Int32 time; 
}; 


[DllImport(@"D:\Test\Projects\Release_Build\WeldDll.dll", CallingConvention = CallingConvention.Winapi)] 
public static extern int ModifyListOfControls(ref InfoStruct pInfo, int size, bool flag);// ref InfoStruct pi); 

public static void Main() 
{ 
    InfoStruct temp = new InfoStruct(); 

    temp.Pointer = new IntPtr(); 

    ModifyListOfControls(ref temp, 200, true); 

    Console.WriteLine(temp.ID); 
    Console.WriteLine(temp.Name); 
    Console.WriteLine(temp.time); 
    Console.WriteLine(temp.value); 


    Console.ReadLine(); 
} 

/* ** * **輸出* ** * ** * * 嗨 20.23 * ** * ** * ** * ** * ** * ** * */

+0

謝謝。一次只傳遞一個結構時效果很好。原來的功能是傳遞一個大小爲「size」的數組,我認爲這是行不通的。我創建了一個新的函數,只返回我需要的索引處的結構。 – diditexas