2010-10-18 72 views
0

我從加載運行時的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的!

+0

發表您的代碼失敗 – 2010-10-18 11:41:29

+0

任何人請幫助我! – Swanand 2010-10-25 09:01:23

回答

0

我不認爲釘住會幫助你在這裏。 CLR將確保您傳遞給互操作調用的任何參數不會在內存中移動,直到調用返回。

所以當你需要做一些手動固定的唯一情況是你調用的函數存儲指針並在稍後寫入。

要知道爲什麼會出現訪問衝突,我們需要更多關於您所調用的本地函數(如函數簽名)的信息。

+0

函數簽名是extern「C」long WINAPI ReadMessage(unsigned long ConnectionID,MsgFormat * pMsg);我不知道更多關於這個功能因爲我把它作爲API。謝謝你的幫助。我還應該爲你提供什麼? – Swanand 2010-10-18 13:17:31