![](/img/trans.png)
[英]Calling unmanaged C DLL function from C# (with pointer to struct and pointer to bool array)
[英]calling unmanaged dll function that returns an array of struct using C#
我正在使用C ++編寫非托管dll。 我可以從C#應用程序輕松調用某些函數。 但是一個功能讓我受苦:)
問題出在log參數中。 它應該反映為Data_Struct
類型的數組:
typedef struct
{
unsigned int id;
unsigned short year;
unsigned char month;
unsigned char day;
unsigned char hour;
unsigned char min;
unsigned char sec;
unsigned char status;
}Data_Struct;
int Read_Stored_Data(HUNIT pUnitHandle, int option, int updateFlag,
int maxEntries, unsigned char *log)
public struct Data_Struct
{
public uint id;
public ushort year;
public byte month;
public byte day;
public byte hour;
public byte min;
public byte sec;
public byte status;
}
[DllImport("SData.dll", EntryPoint = "Read_Stored_Data")]
public static extern int Read_Stored_Data(int pUnitHandle, int option,
int updateFlag, int maxEntries, ref Data_Struct[] log);
請假設我正在傳遞帶有正確值的pUnitHandle
, option
, updateFlag
和maxEntries
。 問題是最后一個參數( log
):
Data_Struct[] logs = new Data_Struct[1000];
res = Read_Stored_Data(handle, 1, 0, 1000, ref logs); // This should work but it
// causes the application
// to terminate!
任何想法?
嘗試使用PInvoke屬性。
具體來說,將布局應用於結構:
[StructLayout(LayoutKind.Sequential)]
public struct Data_Struct
{
public uint id;
public ushort year;
public byte month;
public byte day;
public byte hour;
public byte min;
public byte sec;
public byte status;
}
並在刪除ref
同時對參數應用編組屬性:
[DllImport("SData.dll", EntryPoint = "Read_Stored_Data")]
public static extern int Read_Stored_Data(int pUnitHandle, int option,
int updateFlag, int maxEntries, [MarshalAs(UnmanagedType.LPArray), Out()] Data_Struct[] log);
看看是否有幫助,請進行相應調整。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.