title: Call matlab shared library from dotnet core on linux
body: <p>I am trying to call a shared library created with MathWorks MATLAB Compiler SDK from C# (.NET Core) running on a Linux container.</p>
  
  <p>I have a matlab .m file that I've compiled into a .dll using the MATLAB R2018b compiler SDK. Because the final execution environment is .NET Core 2.2 running on a Linux container I chose the "C Shared Library" option. I call that shared library using the DLLImport mechanism of .NET.</p>
  
  <p>Here is some code from my project. This code is KISS-level because I need to understand how to integrate MATLAB and C# on Linux before I start on the main project. </p>
  
  <p>haveSomePi.m</p>
  
  <pre><code>function hal = haveSomePi()
      hal = 3.1415;
  end
  </code></pre>
  
  <p>MyMath.h</p>
  
  <pre><code>extern LIB_MyMath_C_API bool MW_CALL_CONV mlfHaveSomePi(int nargout, mxArray** hal);
  </code></pre>
  
  <p>MyMathWrapper.cs</p>
  
  <pre><code>[DllImport("MyMath.dll", CallingConvention = CallingConvention.Cdecl)]
  public static extern void mlfHaveSomePi(int nargout, ref IntPtr hal);
  </code></pre>
  
  <p>MyMathWrapperTests.cs</p>
  
  <pre><code>[TestMethod]
  public void ShouldReturnPi()
  {
      var hal = IntPtr.Zero;
  
      MyMathWrapper.mlfHaveSomePi(1, ref hal);
  
      double result = (double)hal; 
  
      Assert.AreEqual(3.1415, result, 1e-5);
  }
  </code></pre>
  
  <p>The expected result is that the assert in the test method passes. It fails because trying to cast an IntPtr to a double doesn't make sense in this context. I'm sure there is a way to de-reference the IntPtr to get at the underlying double, I just haven't found that particular nugget of information.</p>
  
  <p>I have been successful when compiling the .m file into a .NET library and into a COM object. I don't think I can use either of those libraries on Linux because of differences in the binary load/link format for each OS. When calling the method in the COM object I was able to directly cast the IntPtr to a double, there must be some marshaling magic going on in the background.</p>
  
  <ol>
  <li>Is the method signature for the DLLImport statement correct? Do I map mxArray** to IntPtr?</li>
  <li>How do I get the double from the IntPtr? Copy a block of memory into a managed byte array and cast?</li>
  </ol>
  
  <p>My ultimate goal is to access a large signal processing library of matlab code from dotnet. The matlab code uses a lot of vectors and arrays so getting those into and out of the unmangaged library is my next hurdle.</p>
  
  <p>Best regards.</p>