2015-01-28 5 views
-1

이름이 공유 메모리를 읽는 Win32 C++ DLL이 있습니다. 앱에서 C# 응용 프로그램에 수신하는 값을 내보내려고합니다. 사실C# Named Shared Memory 판독기 변수를 C# App으로 내 보냅니다.

,이 코드를 가지고,하지만 난 C# 응용 프로그램에서 값을 액세스 할 때,이 나타납니다

An unhandled exception of type 'System.AccessViolationException' occurred in ETS2 Utilities.exe 

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. 

C++ 코드 :

extern "C" { 
    __declspec(dllexport) int __cdecl returnGear(); 
} 

extern int __cdecl returnGear() 
{ 
    return shared_memory->gear; 
} 

C# 코드 :

[DllImport("ETS2_Utilities_Plugin.dll")] 
public static extern int returnGear(); 

void GetData() 

{ 
    res = returnGear(); 
    lblMarcha.Text = "Marcha: " + res; 
} 
+0

이 질문은 도움이 될 수도 있습니다 - http://stackoverflow.com/questions/18208084/proper-calling-convention-of-unmanaged-dll-function ('CallingConvention = CallingConvention.Cdecl'을'DllImport' 속성). –

+0

C++ 코드를 디버깅해야합니다. 분명히 불만입니다. 프로젝트 + 속성, 디버그 탭에서 "네이티브 코드 디버깅 사용"옵션을 선택합니다. 함수의 진입 점에 중단 점을 설정하여 디버거가 작동하는지 확인하고 디버거가 어디에서 불면되는지 확인합니다. –

답변

0

p/invoke의 호출 규칙이 잘못되었습니다. 다음과 같아야합니다.

[DllImport("ETS2_Utilities_Plugin.dll", CallingConvention = CallingConvention.Cdecl)] 
public static extern int returnGear(); 

그러나 귀하의 문제는 의심 스럽습니다. 나는 실제 문제가 shared_memory이 유효한 메모리를 가리키고 있지 않다라고 생각한다. 아마도 shared_memorynullptr입니다.

인터롭의 빠른 테스트,이 당신의 unmamaged 기능을 대체 :

int __cdecl returnGear() 
{ 
    return 42; 
} 

를이는 상호 운용성이 괜찮지 만, 관리되지 않는 라이브러리가 제대로 초기화되지 않고 있음을 알려줍니다 그 다음 작동하는 경우.

비고 returnGear 기능 정의에 extern을 사용했습니다. 그것은 실수입니다. 위와 같이 제거하십시오.

+0

return 42를 넣으면 C# 응용 프로그램에 42가 반환됩니다. Null 포인터? 콘솔 응용 프로그램에서 내가 할 경우 : cout << shared_memory-> gear; 값이 인쇄됩니다. –

+0

shared_memory는 어디에서 초기화 되었습니까? –

+0

David Heffernan : telemetry_state_t * shared_memory = NULL; 메인() : shared_memory = static_cast (MapViewOfFile (memory_mapping, FILE_MAP_ALL_ACCESS, 0, 0, 0)); –

관련 문제