c# - 尝试读取或写入 protected 内存。这通常表明其他内存已损坏

标签 c# c++ dllimport access-violation

我在尝试将字符串数组从 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/

相关文章:

c++ - 在 C++ 中创建 DLL 以在 VS 2005 中导入 C++ DLL

c++ - 如何将 C++ 插件安装到 Eclipse?

c++ - 枚举位域容器类

c# - 在 C# 中存储 SqlServer 的 raiserror 消息

c# - 绑定(bind)和标记扩展设计器构造函数错误

c++ - Tcl.h : no such file or directory

c# - 如何为c#窗口应用程序创建opencv dll

c++ - 为什么L在dll路径之前?

c# - 如何使我的代码诊断语法节点操作对已关闭的文件起作用?

c# - 使用 HTMLAgilityPack 仅提取页面文本