Reputation: 417
I'm getting this error while trying to pass array of string 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 it is invoked from c#?
//List<string> installedRooms = new List<string>();
//installedRooms.add("r1");
//installedRooms.add("r1"); etc
NativeDetectorEntryPoint.InstalledRooms(installedRooms.ToArray(),installedRooms.Count);
Error is raised at
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 will be truly appreciated
Upvotes: 3
Views: 2389
Reputation: 14919
This is just a guess but since the error is intermittent I believe this is a memory issue related to the string
array installedRooms
.
If you do not mark a managed object using Fixed
keyword, GC
may change the location of the object at any time. Thus, when you try to access to the related memory location from unmanaged code, it may throw error.
You may try the following;
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);
}
Upvotes: 1