2013-02-07 2 views
3

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; 
} 

?

//List<string> installedRooms = new List<string>(); 
//installedRooms.add("r1"); 
//installedRooms.add("r1"); etc 
NativeDetectorEntryPoint.InstalledRooms(installedRooms.ToArray(),installedRooms.Count); 

오류가 어떤 도움이 정말 이건 그냥 추측이지만 오류가 간헐적이기 때문에 나는이가 string 관련 메모리 문제라고 생각

+0

그것은 수있을 당신의 P/(그러나 이것은 완전한 추측!)을 모두 StringBuilder를 사용해야 선언을 호출 : 공공 정적 통근 무효 InstalledRooms (StringBuilder의 [] 객실, INT 길이); –

+1

[MarshalAs (UnmanagedType.LPArray)] string [] rooms – TheMathemagician

+1

@MatthewWatson을 추가하십시오.이 http://stackoverflow.com/questions/1713288/c-passing-array- of-strings-to-ac-dll –

답변

1

을 이해할 수있을 것이다

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) 

에서 발생 배열 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

두 개의 스레드를 사용하여 문제를 시뮬레이트하려고했습니다. 하나를 루프에서 C#에서 C++로 배열을 보내도록 스레드하십시오. 2. 쓰레기 수거를위한 두 번째 스레드. 그러나 이것은 결코 버그를 재현하지 못했습니다. 버그를 재현하고 솔루션을 확실하게 테스트 할 수있는 더 좋은 방법이 있습니까? @daryal –

+0

귀하의 솔루션을 사용할 수 없습니다, 나는 '고정 (char * p = roomsArray)'에 대한 컴파일 시간 오류가 발생합니다. 오류는 다음과 같습니다. 주소를 가져 오거나 크기를 가져 오거나 관리되는 유형 ('문자열')에 대한 포인터를 선언 할 수 없습니다. [link] http://stackoverflow.com/questions/2559384/cannot-take-the-address-of-get-the-size-of-or-declare-a-pointer-to-managed-t 문자열의 배열은 고정 유형 일 수 없습니다. –

관련 문제

 관련 문제