簡體   English   中英

System.AccessViolationException。 嘗試讀取或寫入受保護的內存

[英]System.AccessViolationException. Attempted to read or write into protected memory

我知道已經討論過相同的問題。 我正在使用.dll庫(最初使用C ++編寫,調用約定為stdcall)。 我需要的功能描述如下:

function EKSIS_COM_Read(aPortName: PAnsiChar; aPortSpeed: Integer; aID: Integer; aMem: AnsiChar; aAddr: Word; aData: PByte; aCount: Word): Boolean;
bool EKSIS_COM_Read(char[] aPortName, int aPortSpeed, int aID, char aMem, WORD aAddr, BYTE aData, WORD aCount);

參數說明:

aPortName – com-port (example «COM2»);
aPortSpeed –data rate;
aID –device address;
aMem – memory type (I,R,F);
aAddr –register address;
aData – a pointer to the memory address where the reading will be held;
aCount – the number of bytes read.

在使用c#的VS 2013中,我編寫了以下代碼:

[DllImport("EksisExchange.dll", EntryPoint = "EKSIS_COM_Read", CallingConvention = CallingConvention.StdCall)]
public static extern bool Read(char[] aPortName, int aPortSpeed, int aID, char aMem, ushort aAddr, ref float aData,
   ushort aCount);

但是有時在仿真過程中我會犯錯誤:

System.AccessViolationException。 嘗試讀取或寫入受保護的內存。

為什么會這樣呢? 為什么只在某些時候發生呢?

[DllImport("EksisExchange.dll", EntryPoint = "EKSIS_COM_Read", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
public static extern bool Read(string aPortName, int aPortSpeed, int aID, char aMem, ushort aAddr, byte[] aData, ushort aCount);

您必須將ANSI,以null終止的字符串傳遞給該函數。 最簡單的方法是傳遞字符串,讓封送處理程序完成工作。 同為aMem

aData是將在其中讀取數據的緩沖區。 它必須是一個緩沖區,例如byte[] 調用方法之前創建它。 您將緩沖區的大小放在aCount

該簽名應與以下內容一起使用:

byte[] buffer = new byte[1024];
bool res = Read("COM1", 19200, 1, 'I', 123, buffer, (ushort)buffer.Length);

請注意,此簽名是不合邏輯的:方法沒有地方可以返回已讀取的字節數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM