c # — Попытка чтения или записи в защищенную память. Это часто указывает на то, что другая память повреждена

Я получаю эту ошибку при попытке передать массив строк из 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)

Любая помощь будет по достоинству оценена

3

Решение

Это всего лишь предположение, но, так как ошибка периодически, я считаю, что это проблема памяти, связанная с 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);
}
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector