[英]How pass a structure containing a void* from c++ to c#?
我遇到問題,無法在網上找到答案。 我想從我的C#代碼中調用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 *結構上犯了一個錯誤,但我不知道該放什么。 函數返回一個結構數組的事實也可能是事實,也許我沒有正確地稱呼它。 你能幫我嗎? 非常感謝。
我已經創建了一個測試應用程序,並且代碼在下面,並且工作正常...
// 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();
}
/ * ** * ** 輸出 * ** * ** * * 10高50 20.23 * ** * ** * ** * ** * ** * ** * * * /
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.