| Products & Services | Solutions | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → MATLAB Builder NE |
| Contents | Index |
| Learn more about MATLAB Builder NE |
| On this page… |
|---|
Example: Using functions engOpen and engEvalString from the MATLAB Engine API in a C# Program |
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.
Open Microsoft Visual Studio .NET.
Select File > New > Project.
Select Visual C# Applications in the left pane and Console Application in the right pane. Click OK.
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();
}
}
}
![]() | Blocking Execution of a Console Application that Creates Figures | Handling Errors | ![]() |

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 |