我在嘗試從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)
提出任何幫助將真正的讚賞
這可能是你的P/Invoke聲明應該使用一個StringBuilder(但是這是一個完整的猜測!):公共靜態外部無效InstalledRooms(StringBuilder的[]房間,INT長度); –
嘗試添加[MarshalAs(UnmanagedType.LPArray)]字符串[]房間 – TheMathemagician
@MatthewWatson我不知道你是正確的,也根據這個http://stackoverflow.com/questions/1713288/c-passing-array- of-strings-to-ac-dll –