我在尝试将字符串数组从 C# 传递到 C++ 时遇到此错误。此错误有时会出现,但并非总是会出现。
C#中的声明
[DllImport(READER_DLL,
CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
public static extern void InstalledRooms(string[] rooms,int length);
在 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;
}
它是如何从c#调用的?
//List<string> installedRooms = new List<string>();
//installedRooms.add("r1");
//installedRooms.add("r1"); etc
NativeDetectorEntryPoint.InstalledRooms(installedRooms.ToArray(),installedRooms.Count);
错误发生在
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)
任何帮助将不胜感激
最佳答案
这只是一个猜测,但由于错误是间歇性的,我相信这是与 string
数组 installedRooms
相关的内存问题。
如果您不使用Fixed
关键字标记托管对象,GC
可能会随时更改对象的位置。因此,当您尝试从非托管代码访问相关内存位置时,可能会引发错误。
您可以尝试以下方法;
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);
}
关于c# - 尝试读取或写入 protected 内存。这通常表明其他内存已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14751938/