3

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

任何帮助将不胜感激

4

1 回答 1

1

这只是一个猜测,但由于错误是间歇性的,我相信这是与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);
}
于 2013-02-07T13:27:08.640 回答