-1

I have Win32 C++ DLL that reads a named shared memory, I want to export these values that the app receives to a C# application.

Actually, I have this code, but when I will access the values in C# App, I receive this:

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++ code:

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

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

C# code:

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

void GetData()

{
    res = returnGear();
    lblMarcha.Text = "Marcha: " + res;
}
Daniel Kelley
  • 7,579
  • 6
  • 42
  • 50
  • This question might help - http://stackoverflow.com/questions/18208084/proper-calling-convention-of-unmanaged-dll-function (note the inclusion of `CallingConvention = CallingConvention.Cdecl` in the `DllImport` attribute). – Daniel Kelley Jan 28 '15 at 15:44
  • You need to debug the C++ code, clearly it is unhappy. Project + Properties, Debug tab, tick the "Enable native code debugging" option. Set a breakpoint on the function's entrypoint to verify that the debugger is functional and see where it blows from there. – Hans Passant Jan 28 '15 at 16:05

1 Answers1

0

The p/invoke has the wrong calling convention. It should be:

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

However, I doubt that's your problem. I suspect that the real problem is that shared_memory is not pointing to valid memory. Quite likely is that shared_memory is nullptr.

As a quick test of the interop, replace your unmamaged function with this:

int __cdecl returnGear()
{
    return 42;
}

If this works then that tells you that the interop is fine, but your unmanaged library is not being initialised properly.

One final note, you used extern in your definition of the unmanaged returnGear function. That is a mistake. Remove it, as I have done above.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490