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 に答える