3

We want to use functions written in matlab in our new python application. We want to use ctypes because the user won't need matlab on his machine. We are testing this method but can't get it to work. We lack c knowledge (and much more...). This is our simple test matlab function:

function [ z ] = adding( x,y ) 
    z = x + y; 
end

We compiled this with matlab into a shared library .dll. In a python interpreter we have:

import ctypes
dl = ctypes.CDLL('adding.dll') 

Now we are stuck because we can't find the command to access the function in matlab.
What should we do ?

Shai
  • 111,146
  • 38
  • 238
  • 371
ArtDijk
  • 1,957
  • 6
  • 23
  • 31

2 Answers2

2

Short answer - No.

You can not export code written in MATLAB as C in form of DLL and interface with it using ctypes on python side, so that you can afterwards expect a serious performance boost over usual communication via unix pipe (as in mlabwrapper).

The problem is that such DLL is dependent on MCR (matlab runtime). The DLL contains your source code in an obfuscated form. When you call exported function - the DLL is loaded, which then unpacks the source code, creates an instance of MATLAB (an interpreter) and communicates your code and its results with the MATLAB JIT. This functionality is called "MATLAB compiler toolbox". Alternatively, it can produce OS executables (that follow the same logic).

Rewrite in C/C++ (losing dependency on MATLAB)

If you are not lucky to code-generate your project as in here. Consider rewriting your code in plain C or using C++ libraries as IT++ or Armadillo.

Yauhen Yakimovich
  • 13,635
  • 8
  • 60
  • 67
  • 1
    Indeed, [Armadillo](http://arma.sourceforge.net/) is a great help for converting Matlab programs into C++, as it provides a [Matlab-like API](http://arma.sourceforge.net/docs.html). – mtall Aug 19 '13 at 04:27
  • Can we access the DLL if the runtime is installed? http://in.mathworks.com/products/compiler/mcr/index.html – Nidhin Bose J. Sep 03 '15 at 10:25
1

There are many resources/tutorials available explaining how to use ctypes and call functions inside a dll. See for example this SO question.

If I remember correctly the matlab compiler should properly export all the functions from the dll so they should be accessible from ctypes. However, you will have to ensure the matlab libraries / runtime are in your library path when you try to load the dll. The matlab site has plenty of docs for this, see for example this tutorial.

Community
  • 1
  • 1
dgorissen
  • 6,207
  • 3
  • 43
  • 52