MATLAB: Howto: mingw-w64 Add-on generated mex function that uses a mingw-w64 generated DLL (R2018b)

dllMATLABmexmingw-w64 add-on

The matlab compiler is the mingw-w64 Add on.
To generate the dll, also system wide mingw-w64 installation is done.
I'm able to generate the mex funtion (at the end the toolchain is described)
After executing the file_mex, the dll is said not to be found, but the dll is in the current directory and in the windows's & matlab path.
'file_mex.mexw64': Missing dependent shared libraries:
'file.dll' required by 'file_mex.mexw64'.
loading the dll with loadlibrary says that
'file_mex.dll' has different architecture than the host.
Note that loadlibrary finds file.dll without problems.
My compiling toolchain:
!gcc -c -DBUILDING_EXAMPLE_DLL file.c
!gcc -shared -o file.dll file.o -Wl,--output-def,file.def,--out-implib,libfile.a
!"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\Hostx64\x64\"lib /def:file.def
mex file_mex.c -L. -lfile -R2018a

Best Answer

The question was originated by an improper installation of system wide mingw-w64, I did mistakenly installed a 32 bit version (msys/mingw).
My other proposed solution, was working just because I was using the MATLAB Add-on provided mingw-w64 compiler, something limited if one intends to develop C libraries to be later interfaced with MATLAB mex files.
The following link can be helpful for those anew in this context .
So, after installing MSYS2 64 bit and gcc using its package management system pacman, the following instructions will work as expected:
Input:
!gcc -c shrlibsample.c
!gcc -o shrlibsample.dll shrlibsample.o -s -shared -Wl,--subsystem,windows,--out-implib,"shrlibsample.lib"
mex -v -g myAddStructByRef.c shrlibsample.lib
struct.p1 = 4; struct.p2 = 7.3; struct.p3 = -290;
[res,st] = myAddStructByRef(struct)
Output: C Struct: p1: 4.000000 p2: 7 p3: -290
Calculated sum: -279.000000
res =
struct with fields:
p1: 5.5000
p2: 1234
p3: 12345678
st =
-279
For anybody trying to reprodue this, I nave removed mex references from shrlibsample.c