How can I use/start a MATLAB file, compiled to an exe-file, with C#? I have created a 3D plot in MATLAB, which I want to execute in C#. Is it possible?
This C# code I found:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
// Create the MATLAB instance
MLApp.MLApp matlab = new MLApp.MLApp();
// Change to the directory where the function is located
matlab.Execute(#"cd c:\temp\example");
// Define the output
object result = null;
// Call the MATLAB function myfunc
matlab.Feval("myfunc", 2, out result, 3.14, 42.0, "world");
// Display result
object[] res = result as object[];
Console.WriteLine(res[0]);
Console.WriteLine(res[1]);
Console.ReadLine();
}
}
}
The Mathworks website from which you have your example also explains what you have to do to make it work.
1. Create a MATLAB function, myfunc, in the folder c:\temp\example.
function [x,y] = myfunc(a,b,c)
x = a + b;
y = sprintf('Hello %s',c);
Create the C# application.
In Microsoft® Visual Studio®, add a reference to your C# project to the MATLAB COM object. From the Project menu, select Add Reference.
Select the COM tab in the Add Reference dialog box.
Select the MATLAB application.
Related
I am new at C#.net and I am trying to just Execute the matlab script through visual studio C#.net.I added matlab com reference
The following is my code
MLApp.MLApp matlab = new MLApp.MLApp();
matlab.Execute(#"cd path");
However when I run this code in visual studio, no thing appears in the matlab.
Can you please advise what is my problem?
If you follow the instructions from the official Matlab Site, it works.
https://de.mathworks.com/help/matlab/matlab_external/call-matlab-function-from-c-client.html
If you create it in the same folder as mentioned on the site, everything should work as expected. I just tried it with an WPF application.
Create a MATLAB function, myfunc, in the folder c:\temp\example.
function [x,y] = myfunc(a,b,c)
x = a + b;
y = sprintf('Hello %s',c);
and then the C# application
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
// Create the MATLAB instance
MLApp.MLApp matlab = new MLApp.MLApp();
// Change to the directory where the function is located
matlab.Execute(#"cd c:\temp\example");
// Define the output
object result = null;
// Call the MATLAB function myfunc
matlab.Feval("myfunc", 2, out result, 3.14, 42.0, "world");
// Display result
object[] res = result as object[];
Console.WriteLine(res[0]);
Console.WriteLine(res[1]);
Console.ReadLine();
}
}
}
I have been using edge.js to call a C# function from within my Node.js app, however when I go to execute the C# code I get for example:
Metadata file 'System.Collections.Generic.dll' could not be found
Metadata file 'System.Text.dll' could not be found
...
My code is this below, basically wanting to run a SSIS package using a stored procedure which I am calling from C#. Basically all my referenced dll's can't be found? Where should I put the dlls for edge to find them?
var executeSQL = edge.func(function() {
/*
#r "System.Data.dll"
#r "System.Collections.Generic.dll"
#r "System.Linq.dll"
#r "System.Text.dll"
using System.Linq;
using System.Text;
using System.Data;
using System.Collections.Generic;
using System.Threading.Tasks;
public class StartUp
{
public async Task<object> Invoke(object input)
{
string result = string.Empty;
string packagePath = #"\SSISDB\test\package.dtsx";
string spName = "storedProcName";
using (var conn = new System.Data.SqlClient.SqlConnection("connectionString"))
using (var command = new System.Data.SqlClient.SqlCommand(spName, conn)
{
CommandType = System.Data.CommandType.StoredProcedure
})
{
conn.Open();
command.Parameters.AddWithValue("#PackagePath", packagePath);
command.ExecuteNonQuery();
Console.WriteLine("Finished");
};
return null;
}
}
*/
});
I know I can do this without C# and just use a module within node like mssql to execute the stored procedure but this was just an example test to get used to using edge.js
The comment from stuartd was correct in the sense to put the dlls under the same directory as the script (which I had tried) but I was still having the same issue. I solved my problem by having my C# code as a separate file and then referenced that file as below as part of the executeSSIS function. payload is just the object that gets passed from my node.js script to my C# script. Doing it this way solved my issue.
var payload = {
filePath: 'C:/temp/xlsx/' + req.file.filename,
path: req.packageName,
server: req.server
};
var executeSSIS = edge.func({
source: __dirname + '/cs/Program.cs',
references: [
__dirname + '/cs/System.Data.dll'
]
});
executeSSIS(payload);
Can anyone tell me, how to use methods from C# in ironpython?
I know some basics but don't understand what to do if I don't want to build my C# project as .dll?
Code for the ConsoleApplication1.exe:
using System;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
namespace ConsoleApplication1 {
class Program
{
static void Main()
{
ScriptEngine engine = Python.CreateEngine();
engine.ExecuteFile("C:/Users/Vlad/Desktop/kal.py");
}
public int Plus(int a, int b)
{
int z = a + b;
Console.WriteLine(z);
return z;
}
}
}
//kal.py
print 'test1'
import clr
clr.LoadAssemblyFromFile("C://Users/Vlad/Documents/Visual Studio 2015/Projects/ConsoleApplication1/ConsoleApplication1/bin/Debug/ConsoleApplication1.exe")
import ConsoleApplication1
arith = ConsoleApplication1.Program.Plus(10,20)
print arith
just change type of C# application to Class library and reference it to your
python app.
from solution explorer right click on C# project note and click Properties and change appliction type to class library.
you can reference a library to the project from Project>add reference menu.
There's already a similar answered question in this post
but this one is different: I actually do not get a IronPython.Runtime.List (I do have using System.Linq;) from a call like Func<IList<double>> get_a_list = pyOps.GetMember<Func<IList<double>>>(class1, "get_a_list"); where get_a_list is the Python code that returns a Python [] list. I get a {IronPython.Runtime.ListGenericWrapper<double>}. How can I convert that to a C# List?
See the code below - all works fine except for getting the x variable into C#.
class class1(object):
"""Support demo of how to call python from C#"""
def __init__(self):
self.a = 5
def get_a_square(self):
return pow(self.a,2)
def get_a_times_b(self, b):
return self.a*b
def get_a_list(self):
return [self.a,self.a,self.a]
and the C# Code is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System.Reflection;
using System.IO;
namespace DemoUsingPythonModule
{
class Program
{
static void Main(string[] args)
{
ScriptEngine pyEngine = Python.CreateEngine();
// Load the DLL and the Python module
Assembly dpma = Asse mbly.LoadFile(Path.GetFullPath("DemoPythonModule.dll"));
pyEngine.Runtime.LoadAssembly(dpma);
ScriptScope pyScope = pyEngine.Runtime.ImportModule("class1");
ObjectOperations pyOps = pyEngine.Operations;
// Instantiate the Python Class
var classObj = pyScope.GetVariable("class1");
object class1 = pyOps.Invoke(classObj);
// Invoke a method of the class
var a2 = pyOps.InvokeMember(class1, "get_a_square", new object[0]);
Console.Write(a2.ToString()+'\n');
// create a callable function to 'get_a_square'
Func<double> get_a_square = pyOps.GetMember<Func<double>>(class1, "get_a_square");
double a2_2 = get_a_square();
// create a callable function to 'get_a_times_b'
Func<double, double> get_a_times_b = pyOps.GetMem ber<Func<double, double>>(class1, "get_a_times_b");
Console.WriteLine(get_a_times_b(3.0).ToString());
Console.WriteLine(get_a_times_b(4.0).ToString());
Func<IList<double>> get_a_list = pyOps.GetMember<Func<IList<double>>>(class1, "get_a_list");
var x = get_a_list();
Console.WriteLine(x.Cast<double>().ToList().ToString());
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
OK I found it. The type is indeed IronPython.Runtime.ListGenericWrapper<double> but the Python code above returns a list of ints. If I change the constructor to self.a = 5.0 the thing works.
I'd like to use a RubyGem in my C# application.
I've downloaded IronRuby, but I'm not sure how to get up and running. Their download includes ir.exe, and it includes some DLLs such as IronRuby.dll.
Once IronRuby.dll is referenced in my .NET project, how do I expose the objects and methods of an *.rb file to my C# code?
Thanks very much,
Michael
This is how you do interop:
Make sure you have refs to IronRuby, IronRuby.Libraries, Microsoft.Scripting and Microsoft.Scripting.Core
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronRuby;
using IronRuby.Builtins;
using IronRuby.Runtime;
namespace ConsoleApplication7 {
class Program {
static void Main(string[] args) {
var runtime = Ruby.CreateRuntime();
var engine = runtime.GetRubyEngine();
engine.Execute("def hello; puts 'hello world'; end");
string s = engine.Execute("hello") as string;
Console.WriteLine(s);
// outputs "hello world"
engine.Execute("class Foo; def bar; puts 'hello from bar'; end; end");
object o = engine.Execute("Foo.new");
var operations = engine.CreateOperations();
string s2 = operations.InvokeMember(o, "bar") as string;
Console.WriteLine(s2);
// outputs "hello from bar"
Console.ReadKey();
}
}
}
Note, Runtime has an ExecuteFile which you can use to execute your file.
To get the Gems going
Make sure you install your gem using igem.exe
you will probably have to set some search paths using Engine.SetSearchPaths