2

I have a control problem which i solved by using Model predictive control (MPC). I have stated the problem in MATLAB and used FORCES http://forces.ethz.ch/ to solve it. FORCES is a web service from ETH Zürich which generates library-free ANSI-C code. For testing the code they provide a script to compile the c-code to a MATLAB .mex file. This all works great.

I now want to use this function in my C# Windows Forms programm. To use C-code in C# I have to compile the c-code to a dll and then use P/Invoke? Or is there an other way? How can I compile it? Can I just use the code as it is or do I have to edit it (adding __declspec or something like that)? Is it possible to compile the dll directly out of MATLAB?

The .c and .h files can be found on my homepage: http://n.ethz.ch/~rehofman/download/.

I run 64bit Windows 7, MATLAB 2013b, Visual Studio 2012.

I have MinGW already installed if that is needed.

EDIT:

Ok here is a more specific question: I have a function(myMPC_solve) written in c-code which I want to call from c#. What is the best way to do so? The arguments and datatypes are all in the .h file.

  • PInvoke is the only way. – Bauss Dec 02 '13 at 15:36
  • 1
    You asked many questions in this post, lots of ways to answer some of them, but regarding these: _How can I compile it?_, ***[HERE](http://www.mingw.org/wiki/sampleDLL)*** is a link showing how you can compile. Regarding _P/Invoke_ there are many ***[other links](http://msdn.microsoft.com/en-us/library/aa288468%28v=vs.71%29.aspx)*** (here is one) showing how to use a standard .dll, (or as Microsoft calls it _unmanaged code_) – ryyker Dec 02 '13 at 15:40
  • By the way, Your question is interesting, and it shows you have done some work, but it will not be very easy for someone to really help answer your questions because it is pretty broad, and not self contained. take a look at this link regarding these comments: ***[SSCCE](http://sscce.org/)*** – ryyker Dec 02 '13 at 15:50
  • @L33TS pinvoke is not the only way – David Heffernan Dec 02 '13 at 16:51

1 Answers1

0

You could do any one of the following:

  1. Compile the C code to a DLL, and include it using p/invoke.
  2. Compile the C code into a C++/CLI mixed mode assembly, wrap the functionality in a ref class, and consume that from C#
  3. Wrap the C code with a COM server and consume that from C#.
  4. Leave the code in MATLAB and consume that from C#. There are multiple ways in which MATLAB code can be consumed by C# code.

And I'm sure there are other options beyond the above.

Now, if you are hoping for a detailed step-by-step instruction of what to do next, I'm sorry to disappoint you. You asked a broad question and I've given you a correspondingly broad answer. What you should do next is to pick one of the options above, and implement it. When you get stuck, do feel free to ask a more specific question.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490