An attempt was made to read or write protected memory. This is often a sign that other memory is damaged.
I am getting this error when trying to pass an array of strings from C # to C ++. This error appears sometimes, not always.
Declaration in C #
[DllImport(READER_DLL,
CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
public static extern void InstalledRooms(string[] rooms,int length);
In C ++
void InstalledRooms(wchar_t const* const* values, int length);
void DetectorImpl::InstalledRooms(wchar_t const* const* values, int length)
{
LogScope scope(log_, Log::Level::Full, _T("DetectorImpl::InstalledRooms"),this);
std::vector<std::wstring> vStr(values, values + length);
m_installedRooms=vStr;
}
How is it called from C #?
//List<string> installedRooms = new List<string>();
//installedRooms.add("r1");
//installedRooms.add("r1"); etc
NativeDetectorEntryPoint.InstalledRooms(installedRooms.ToArray(),installedRooms.Count);
The error occurs when
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at MH_DetectorWrapper.NativeDetectorEntryPoint.InstalledRooms(String[] rooms, Int32 length)
Any help would be really appreciated
source to share
This is just a guess, but since the error is intermittent, I believe this is an array related memory issue string
installedRooms
.
If you do not tag the managed object with a keyword Fixed
, it GC
can change the location of the object at any time. Thus, when you try to access a linked memory location from unmanaged code, it can throw an error.
You can try this:
List<string> installedRooms = new List<string>();
installedRooms.add("r1");
installedRooms.add("r2");
string[] roomsArray = installedRooms.ToArray();
fixed (char* p = roomsArray)
{
NativeDetectorEntryPoint.InstalledRooms(p, roomsArray.Count);
}
source to share