Trouble with C#<->C++ DLLImport "Attempted to read or write protected memory."

Try changing [In] to [In, Out]. I'm also not sure about using both the ref and [In, Out] keywords together on a single argument. (Edit: Hans Passant has a good explanation of the differences between the two in his comment below.)

See this MSDN article for more information, especially the passage, "By default, reference types (classes, arrays, strings, and interfaces) passed by value are marshaled as In parameters for performance reasons. You do not see changes to these types unless you apply InAttribute and OutAttribute (or just OutAttribute) to the method parameter."


I started getting this exception durring native interop periodically after upgrading to Windows 7. The code had always worked on XP and has fewer issues on Win 7 if I ran my app in XP compatibility mode.

After some research and experimentation I discovered that the reason I was getting this exception had to do with calling a native function that returned a string (WCHAR*).

I don’t believe there is currently a fix for this as even updating to .Net 3.5 didn’t fix the issue… However I did find the following work around.

Example of what works on XP but doesn’t work on Win 7:

[DllImport("NativeBin.dll")]
public static extern String GetWCharStr();

Example of what works for me on Win 7 and XP:

[DllImport("NativeBin.dll")]
private static extern IntPtr GetWCharStr();
public static String GetString()
{
    return Marshal.PtrToStringUni(GetWCharStr());
}