Hi,
I'm trying to call a dll from C#, but get System.AccessViolationException. Besides the three long arguments, the fourth is a structure, which should be passed as a reference, because the dll writes data into it. That's where the error occurs: "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

I managed to get an answer to similar question five years ago when struggling with the same problem, but with VB5 at that time. Now I'm trying to port the code in c#.

See the discussion from: http://www.vbforums.com/archive/index.php/t-375387.html

The code in VB which works is:
Code:
 Declare Function OCIRead Lib "oci200.dll" (ByVal lOIObject As Long, ByVal lDevice As Long, ByVal lIndex As Long, pOIData As OIDATA) As Long
--------------------------
Public Type OIDATA
  lData(0 To 31) As Long     'array of data, values depeds of index number
  lCheckAlarm As Long   'when read request is done and this is > 0 user should check alarm
  lCategory As Long     'when this is > 0 device configuration is changed
  lReadError As Long    'read error is occured
  szData(0 To 127) As Byte   'String * 128 'raw index read data as comma separated
End Type
-----------------------

    retdata = OCIRead(lObject, lDevice, lIndex, pOIData)
The same in C# which causes an error above:
Code:
        [DllImport(DllName)]
        public static extern Int32 OCIRead(Int32 lOIObject, Int32 lDevice, Int32 lIndex, ref OIDATA pOIData);
--------------
public struct OIDATA
        {
            public Int32[] lData;            //'array of data, values depeds of index number
            public Int32 lCheckAlarm;       //'when read request is done and this is > 0 user should check alarm
            public Int32 lCategory;         //'when this is > 0 device configuration is changed
            public Int32 lReadError;        //'read error is occured
            public byte[] szData;           // 'String * 128 'raw index read data as comma separated        
        }
----------------------
            public OIDATA pOIDATA;
  
            pOIDATA.lData = new Int32[32];
            pOIDATA.lCategory = 1;
            pOIDATA.lCheckAlarm = 0;
            pOIDATA.lReadError = 0;
            pOIDATA.szData = new byte[128];

            Int32 k = oci.OCIRead(lObject, lDevice, lIndex, ref pOIDATA);
I have replaced Long with int32 in lObject, lDevice and lIndex.
Any ideas?