Using MinGW-w64 from MSYS2 with LibraryLink

I am looking to use the MinGW-w64 version of gcc, as bundled with msys2, with LibraryLink.

It was communicated to me that in recent versions of Mathematica, one may use the MinGWCompiler compiler driver with MinGW-w64 (the documentation page showing the use of GenericCCompiler is outdated).

In particular, it was confirmed to me that the code I included at the end of this post worked for at least one person. However, for me it does not work. At the LibraryFunctionLoad stage, I get

In[12] := add1 = LibraryFunctionLoad[add1lib, "add1", {Integer}, Integer]  During evaluation of In[12] :=   LibraryFunction::libload : The function add1 was not loaded from the file C :\Users\mpi\AppData\Roaming\Mathematica\SystemFiles\LibraryResources\Windows-x86-64\add1.dll. Out[12] = $  Failed  In[13] := LibraryLink`$  LibraryError Out[13] = "Library load error 998: Invalid access to memory location. 

I am looking for advice on debugging this and figuring out what causes this failure. Does it work for anyone else?

I tried this on two computers, and I see the same failure on both:

  • Windows 7 with Mathematica 12.0.0
  • Windows 7 with Wolfram Engine 12.1.0

Here’s a minimal example to test with. This assumes that msys2 was installed at the default location. The example C code is from the CreateLibrary doc page.

In[2]:= Needs["CCompilerDriver`"]  In[3]:= Needs["CCompilerDriver`MinGWCompiler`"]  In[4]:= $  CCompiler = {"Name" -> "MinGW", "Compiler" -> MinGWCompiler,     "CompilerInstallation" -> "C:\msys64\mingw64\bin\gcc.exe",     "CompilerName" -> Automatic};  In[5]:= add1src = "   #include \"WolframLibrary.h\"    DLLEXPORT mint WolframLibrary_getVersion(){     return WolframLibraryVersion;   }    DLLEXPORT int WolframLibrary_initialize( WolframLibraryData libData) {     return 0;   }    DLLEXPORT void WolframLibrary_uninitialize( WolframLibraryData libData) {     return;   }    DLLEXPORT int constantzero(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res){      MArgument_setInteger(Res, 0);      return LIBRARY_NO_ERROR;   }    DLLEXPORT int add1(WolframLibraryData libData,             mint Argc, MArgument *Args, MArgument Res) {     mint I0;     mint I1;     I0 = MArgument_getInteger(Args[0]);     I1 = I0 + 1;     MArgument_setInteger(Res, I1);     return LIBRARY_NO_ERROR;   }    ";  In[6]:= add1lib = CreateLibrary[add1src, "add1", "ShellCommandFunction" -> Print]  In[7]:= add1 = LibraryFunctionLoad[add1lib, "add1", {Integer}, Integer]  In[8]:= add1[10] Out[8]= 11