Products & Services Solutions Academia Support User Community Company

Learn more about MATLAB Builder NE   

Using MATLAB API Functions in a C# Program

Overview

You include functions from MATLAB APIs, such as the Engine API, in your C# code by using the DllImport attribute to import functions from libeng.dll (written in unmanaged C) and then declaring those functions as C# equivalents. The imported Engine functions are called using the P/Invoke mechanism, as illustrated in the example below.

Example: Using functions engOpen and engEvalString from the MATLAB Engine API in a C# Program

  1. Open Microsoft Visual Studio .NET.

  2. Select File > New > Project.

  3. Select Visual C# Applications in the left pane and Console Application in the right pane. Click OK.

  4. Auto-generated code appears. Replace the auto-generated code with this code and run:

    using System;
    using System.Text;
    using System.Runtime.InteropServices;
    
    namespace ConsoleApplication8
    {
        class MatlabEng
        {
            [DllImport("libeng.dll")]
            static extern IntPtr engOpen(string startcmd);
    
            [DllImport("libeng.dll")]
            static extern IntPtr engEvalString(IntPtr engine, 
                                                string Input);
            
            public MatlabEng()
            {
                IntPtr engine;
                engine = engOpen(null);
                if (engine == IntPtr.Zero)
                    throw new NullReferenceException("Failed to 
                                         Initialize Engine");
    
                engEvalString(engine, "surf(peaks)");
            }
    
            ~MatlabEng()
            {
            }
        }
    
    
        class StartProg
        {
            public static void Main()   
            {  
               MatlabEng mat = new MatlabEng();
            }
        }
    }
    

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS