我從加載運行時的DLL(使用LoadLibrary())調用函數。 這個DLL是用C++編寫的,我的代碼是用C#編寫的。 API需要結構指針。我傳遞「ref」而不是指針。固定結構以避免AccessViolationException
雖然這樣做,我得到「AccessViolationException」。經過3天的谷歌搜索,我認爲這個問題可以通過固定結構來解決,以便GC不會打擾它。 (見:Passing struct by reference causing AccessViolationException)
我的問題是我可以釘一個結構,而不使用任何指針?因爲我不想傳遞一個指向函數的指針。
代碼如下:
public class TestClass
{
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]
public struct MsgFormat
{
public Int32 MsgID;
public Int32 RxID;
[MarshalAs(UnmanagedType.ByValArray,SizeConst=13)]
public Char[] MsgData;
}
unsafe public delegate Int32 ReadMessage(Int32 ConnectID,ref MsgFormat Message);
ReadMessage fp_ReadMessage;
void Connection()
{
IntPtr pDLLHandle;
pDLLHandle=LoadLibrary(Connect.dll); // Load Required DLL
IntPtr fPtr= GetProcAddress(pDLLHandle,"ReadMessage");
fp_ReadMessage=(ReadMessage)Marshal.GetDelegateForFunctionPointer(fPtr,typeof(ReadMessage)); // Get Function Pointer for API
}
void Read()
{
MsgFormat Rx_Msg=new MsgFormat();
Int32 nReturnValue;
Int32 nConnectID=0; // Value is assigned for Testing the Function
/* Also Tried:
Rx_Msg.MsgData=new Char[13]; */
nReturnValue= fp_ReadMessage(nConnectID,ref Rx_Msg); // "ReadMessage" will return info in Rx_Msg;
/*呼籲fp_ReadMessage給我 「AccessViolationException」。我試圖做的是裁判甚至通過了IntPtr.Zero我仍收到錯誤*/
}
}
}
問候, Swanand IntPtr的!
發表您的代碼失敗 – 2010-10-18 11:41:29
任何人請幫助我! – Swanand 2010-10-25 09:01:23