2013-02-07 44 views
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) 

提出任何幫助將真正的讚賞

+0

這可能是你的P/Invoke聲明應該使用一個StringBuilder(但是這是一個完整的猜測!):公共靜態外部無效InstalledRooms(StringBuilder的[]房間,INT長度); –

+1

嘗試添加[MarshalAs(UnmanagedType.LPArray)]字符串[]房間 – TheMathemagician

+1

@MatthewWatson我不知道你是正確的,也根據這個http://stackoverflow.com/questions/1713288/c-passing-array- of-strings-to-ac-dll –

回答

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); 
} 
+0

我試圖模擬使用兩個線程的問題1.線程之一從循環發送數組從c#到C++。 2.第二個垃圾回收線程。但是這從來沒有重現錯誤。有沒有更好的方法來重現錯誤,然後確定地測試解決方案。 @daryal –

+0

我無法使用你的解決方案,我得到'fixed(char * p = roomsArray)'的編譯時錯誤。錯誤是:無法獲取地址,獲取大小或聲明指向託管類型('字符串')的指針。按照[鏈接] http://stackoverflow.com/questions/2559384/cannot-take-the-address-of-get-the-size-of-or-declare-a-pointer-to-a-managed-t字符串數組不能爲固定類型 –

相關問題