I'm trying to call a minimal C function from C# on Windows 10. I use mingw/g++ to compile the C code into a .dll
It turns out that I have to define opterator new[]
or compile the .dll using Visual Studio. Otherwise my C# program crashes with the following error:
The program '[14740] Test.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.
I'd really love to understand what exactly is happening here and how I can resolve this issue without overriding all the new/delete operators but still using mingw.
Here's the minimal example reproducing the error including a workaround (if AddNewOperator
is defined operator new[]
will be defined and the resulting .dll will work fine):
Test.cs (compiled/run with Visual Studio 2017):
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("libTest", CallingConvention = CallingConvention.StdCall, ExactSpelling = true)]
public static extern int TestFunction();
static void Main(string[] args)
{
Console.WriteLine("!!" + TestFunction());
}
}
Test.cpp compiled with mingw (see below):
#include <new>
#include <cstdlib>
#ifdef AddNewOperator // This will fix the issue
void* operator new[](std::size_t sz){
return std::malloc(sz);
}
#end
extern "C" {
int __stdcall __declspec(dllexport) TestFunction() {
int* test = new int[3]; // removing this line will make everything work when building
return test[2];
}
And here's the build script:
# Remove the following # and the compiled dll will work just fine
g++ -g -s -Wall -c -fmessage-length=0 Test.cpp #-DAddNewOperator
g++ -g -shared -o libTest.dll *.o -Wl,--subsystem,windows
Edit: compiling everything for x86 instead of 64 bit also fixes the issue (which is again no option for me)