"Attempted to read or write protected memory. This is often an indication that other memory is corrupt. "

  .net, .net-framework-4.8, c++

I am trying to call ‘C’ dll that maps the record to memory location but while calling the dll I am getting error "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

The line of code that is throwing error is:
CoFormattingSupport.PInvoke.UnsafeNative.rtgarapi.MapRec(tmpPtr, ref InRec, ref InStructLen);

Using .NET Framework 4.8, debugging the solution in Mixed mode. The project is compiled in X86

Here is the complete code.

public static void MapRec<T>(ref T OutStruct, ref string InRec, ref short InStructLen) where T : struct 

    { 

        IntPtr tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf(OutStruct)); 

        Marshal.StructureToPtr(OutStruct, tmpPtr, true); 

        CoFormattingSupport.PInvoke.UnsafeNative.rtgarapi.MapRec(tmpPtr, ref InRec, ref InStructLen); 

        OutStruct = (T) Marshal.PtrToStructure(tmpPtr, OutStruct.GetType()); 

    } 

The MapRec dll is called as: (XYZ is renamed from its original dll name just for privacy)

DllImport("XYZ.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] 

    extern public static void MapRec(System.IntPtr  OutStruct, [MarshalAs(UnmanagedType.VBByRefStr)] ref string InRec, ref short InStructLen); 

The C code is like this

VOID VBAPI MapRec(LPSTR InStruct, HLSTR InRec, SHORT *NumBytes) 
{ 
SHORT          CopyBytes; 
USHORT      InRecLen=10; 
InRecLen = VBGetHlstrLen(InRec); 
memset(InStruct,' ',*NumBytes); 
if (*NumBytes > (SHORT) InRecLen)  
    CopyBytes = (SHORT) InRecLen; 
else 
    CopyBytes = *NumBytes; 
memcpy(InStruct, *InRec, CopyBytes);     
return;                                          

}

The same dll is being called from Vb6 without any issue.

Source: Windows Questions C++

LEAVE A COMMENT