I am trying to call the a function in a C++ exe from my C# program. This is dllmain.cpp:
#include <cstdio>
#define EXPORT(type) extern "C" __declspec(dllexport) type __stdcall
EXPORT(void) SetupEngine(HWND handle)
{
printf("asd\n");
}
And this is the P/Invoke declaration and the call:
[DllImport("program.exe", CallingConvention = CallingConvention.StdCall)]
internal static extern void SetupEngine(IntPtr hWnd);
// ...
SetupEngine(IntPtr.Zero);
For some reason, this call results in the following exception:
System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
If I change the function to just simply return an integer then it seems to work, and the C# program receives the int value (which shows that the exported name isn't mangled). But if I put basically any other code in there (including a simple printf) then I get the exception.
Both project's architectures are the same (x86), the .NET version is 4.8 and the c++ platform toolset version is v142 with Windows SDK 10.0.
Am I missing something obvious here?
EDIT
I created a simple VS2019 solution that reproduces the crash.