我在這裏提到了類似的問題,但沒有得到解決我的問題的方法。C中的馬歇爾C++結構#
編組問題。我嘗試C++結構到C#但不能做到這一點。我在pinvoke.net搜索瞭解決方案的任何提示,但找不到任何東西。請幫幫我 !
錯誤消息
An unhandled exception of type 'System.AccessViolationException' occurred in Unknown Module.
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
C++的Structs
typedef struct SDK_ALARM_INFO
{
int nChannel;
int iEvent;
int iStatus;
SDK_SYSTEM_TIME SysTime;
}SDK_AlarmInfo;
typedef struct SDK_SYSTEM_TIME{
int year;
int month;
int day;
int wday;
int hour;
int minute;
int second;
int isdst;
}SDK_SYSTEM_TIME;
轉換結構C#:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SDK_ALARM_INFO
{
public int nChannel;
public int iEvent;
public int iStatus;
[MarshalAs(UnmanagedType.Struct)]
public SDK_SYSTEM_TIME SysTime;
};
public struct SDK_SYSTEM_TIME
{
public int year;
public int month;
public int day;
public int wday;
public int hour;
public int minute;
public int second;
public int isdst;
}
編組指針指向結構時出現錯誤。
C#代碼
private XMSDK.fMessCallBack msgcallback;
bool MessCallBack(int lLoginID, string pBuf,uint dwBufLen, IntPtr dwUser)
{
SDK_ALARM_INFO ai = new SDK_ALARM_INFO();
//getting error bottom line
ai = (SDK_ALARM_INFO) Marshal.PtrToStructure(dwUser, typeof(SDK_ALARM_INFO)); // getting error this line
MessageBox.Show("Event: " + ai.iEvent.ToString() + " - Channel: " + ai.nChannel + " - GTime : " + ai.SysTime);
return form.DealwithAlarm(lLoginID,pBuf,dwBufLen);
}
public int InitSDK()
{
//...
msgcallback = new XMSDK.fMessCallBack(MessCallBack);
XMSDK.H264_DVR_SetDVRMessCallBack(msgcallback, this.Handle);
//...
}
MessCallBack功能C#
class XMSDK {
// ...
public delegate bool fMessCallBack(int lLoginID, string pBuf, uint dwBufLen, IntPtr dwUser);
[DllImport("NetSdk.dll")]
public static extern void H264_DVR_SetDVRMessCallBack(fMessCallBack cbAlarmcallback, IntPtr lUser);
//...
}
我認爲,結構轉換錯誤和可能造成的錯誤。等待幫助。謝謝 !
[請將確切的錯誤消息添加到您的問題。](http://stackoverflow.com/posts/25960751/edit) – 2014-09-21 15:28:27
對不起,我更新了職位。 – 2014-09-21 15:35:43