I have a complicated Matlab function which I would not like to re-write in C#. The function returns an array of N double-precision numbers.
Given that I have compiled the function to into a .NET assembly (a .dll file), and that the function's signature goes like [resutls] = myFunc('stringInput'), how can I call my function inside a C# code?
Thanks!
Here you can find the steps to do that:
https://www.mathworks.com/help/compiler_sdk/gs/create-a-cc-application-with-matlab-code-1.html
Is necessary have the runtime library installed on the computer that run your code (you can add it when create the .dll package)
The way I did it, is by adding MLApp as a project reference.
From MATLAB, you need to start the automation service:
enableservice('AutomationServer', true);
And within C# you can connect to Matlab using.
MLApp.DIMLApp matlabInstance = (MLApp.DIMLApp)Marshal.GetActiveObject("Matlab.Desktop.Application");
You can then use the interface functions of MLApp to interact. E.g.
int a = (int)matlabInstance.GetVariable("variableName", "base");
Or even execute stuff. E.g.:
matlabInstance.Execute("evalin( 'base' , 'plot( range , dataVector , ''k'');' );");
of course you need some error handling, etc. Normal application stuff.
There's a topic about it here
Related
I have a C# class library that contains some specialized mathematical functionality relating to raster processing (it uses some asynchronous techniques to spped up the processing). I have a project that my client wants written using Ruby on Rails (RoR) on a Linux box, that can benefit from using this library (I'd rather not port it to Ruby or C++).
The first part of my question is:
Can a standalone Mono-based DLL be created from my C# DLL? (By standalone I mean, the DLL can be utilized WITHOUT having mono installed (all required libraries would be included in the single DLL)?
And the second part, if the answer to part 1 is 'yes', can this standalone mono-based DLL be called from Ruby?
EDIT 11/22/2014
I have made a little progress possibly. I have created a *.so file by using
mono --aot -O=all dlltest.dll
(Obviously I now have Mono installed on my Ubuntu test VM.) This results in dlltest.so, which I then add a symbolic link for in /usr/lib.
The code for my test Ruby script is:
require 'ffi'
module CsharpTest
extend FFI::Library
ffi_lib 'dlltest.so'
attach_function :Hello, [], :string
end
ret_str = CsharpTest.Hello()
puts ret_str
Note that my simple C# class is:
using Systems;
namespace DllTest
{
public static class MyClass
{
public static string Hello()
{
return "Hello World";
}
}
}
When I run the test Ruby script (ruby test.rb) I get the following error:
....:in 'attach_function': Function 'Hello' not found in [dlltest.so] (FFI::NotFoundError)
Using 'nm -Ca dlltest.so' the available functions are listed. One of them is '0000000000001010 t DllTest_MyClass_Hello'. If I use this label as opposed to 'Hello' I get a similar error.
Also note that 'nm -D --defined-only dlltest.so' does not list any functions with 'Hello' in them.
I'm still not sure if I've on the right track, but is there anything more I can try? Or is this approach a dead end?
I have designed the code in MATLAB and it's working fine. I was working in GUI in MATLAB but it's a headache for me. I think i can create GUI simply and effectively. Can we create GUI in C# that will also run the whole code of MATLAB that i have designed??
Yes, this is possible. For details, take a look at:
Calling a MATLAB function from C#
Integrating MATLAB with C#
MATLAB Compiler
If you need a quick and dirty way to wrap MATLAB code with a C# GUI (e.g. WinForms), one option is to create an exe from your MATLAB code (.m) - from .NET, you can then easily start this exe as a new process. Note that this approach may not be the best in some situations, beacuse the delay introduced with an exe call can be quite substantial (as the other answer explains).
An example: first, write MATLAB code as a function:
function y=SamplePlot(p, d, w, t)
numericValueP=str2num(p);
numericValueD=str2num(d);
numericValueW=str2num(w);
time=str2num(t);
%... do stuff ...
plot(...);
Input parameters will be passed to this code as string parameters via command line, hence they are converted via str2num. E.g. a MATLAB call
SamplePlot('1', '2', '3', '4')
will be represented as
SamplePlot.exe 1 2 3 4
Now, create a standalone console app from .m file: in MATLAB console, write:
deploytool
Name: SamplePlot.prj (for example). Target: Console application.
Add .m file.
Package: add MCR (this is MATLAB Compiler Runtime - this is what an end-user will need if he doesn't have MATLAB installed; for local testing, you don't need to add this).
Then use:
mbuild -setup
Finally, click 'build' icon. After some time, an exe is generated. Now, you can start this exe as a process from a C# application, e.g. on button click:
private void button1_Click(object sender, EventArgs e)
{
string p=TextBox1.Text;
string d=TextBox2.Text;
string w=TextBox3.Text;
string t=TextBox4.Text;
string params = String.Format("{0} {1} {2} {3}",p,d,w,t);
System.Diagnostics.Process.Start("SamplePlot.exe", params);
}
I left out some minor details, but this is one possible option.
(If I recall correctly, an assembly can be generated this way as well; you can then call the assembly instead of an exe file).
I'm pretty unfamiliar with C# but eventually happened to use .NET classes from MATLAB.
So, you could also do it the other way round, than the previous answers suggest:
Since MATLAB is able to create/open .NET gui-elements like dialog, I guess you should also be able to open your .NET-GUI from MATLAB an then plug in your MATLAB-Code via Callbacks.
See e.g.:
http://www.mathworks.de/de/help/matlab/matlab_external/getting-started-with-net.html
Depending on how frequently you want to execute matlab-code from your gui and how long the matlab-processing time usually is, this also avoids the pretty large overhead that's e.g. introduced by using a .exe generated with the MATLAB compiler.
Say, you'd like to do quick matrix-calculation operations taking less than a second with every other button-click, than starting a standalone.exe everytime would make your gui pretty useless.
This link is so useful and simple:
Call MATLAB Function from C# Client
I have the problem loading the DLL file and calling the functions in Python.
I have tried a lot of tutorials, but still can't figure out how it works.
This is my class to export as DLL file. I use simple C# code.
namespace DemoClassLib
{
public class cLib
{
public int increment(int x)
{
return x + 1;
}
}
}
After building the C# code, I get the DLL file called "DemoClassLib.dll".
I use ctypes to load the DLL file. Everything is okay until now.
from ctypes import *
myDll = WinDLL('D:\\Resources\\DemoClassLib\\bin\\Debug\\DemoClassLib.dll')
Starting from that point, I can't continue.
All the commands I have tried are failed.
n = c_int(1)
myDll.increment(n)
It keeps on showing me the errors.
How can I call the method "increment()" in Python?
And how can I pass the input and retrieve the output from that?
I am very new to Python.
Can someone help me please?
I would be very appreciated if you can provide me the source code tutorial.
You can't do this with ctypes because there is no symbol in the binary called simply "increment", as your increment method is a member of a class. Even if this were C++ the name would be mangled. But with C# you don't even get a mangled name in the symbol table because the code is interpreted by the .NET framework.
If you must for some reason interface with a C# library you may want to consider trying IronPython (http://ironpython.net/) which is Python running on the .NET framework with full access to the CLR. The comment above suggesting exposing a COM interface could also work.
I've got a problem which I hope you can help me with.
I created ASP.NET 4.0 web application. I've also got .cpp file generated in some other app. This .cpp file contains functions, which always returns the same number of variables and which always takes the same number of parameters.
What I need to do is being able to use this functions in my web application.
But what is real problem is that I need to be able to replace this functions while running app. What I mean is administrator should be able to login, upload new cpp file, which will replace old functions with new ones. New ones will have the same names, parameters and result number, but will make calculations in a different way.
Is there any way this can be achieved?
Thanks for any help!
MattheW
Precompile the cpp code into dlls and let admin upload dll. Reference dll's from c# app using [DllImport("")] directive.
C++ will need to be compiled in some way or another. You can use a compiled dll written in C++ in your ASP.NET application but the code will still need to be compiled for ASP to be able to use it.
The compiled DLL can then be loaded and unloaded to accommodate changes to the function. You could perhaps even make the ASP.NET server compile the file somehow, but the code still needs to be compileable to a DLL to make it executable.
You need to expose the C++ code via another dll.
The first choice is pinvoke. See:
How to set up a C++ function so that it can be used by p/invoke?
It's also covered here:
http://msdn.microsoft.com/en-us/library/aa446538.aspx
Technically you could also expose via COM or write in managed C++ but those are both overkill if you're just trying to expose a few C++ functions.
How can I use the ListView_GetBkImage macro:
http://msdn.microsoft.com/en-us/library/bb761246(v=VS.85).aspx
... from a C#/WinForms application? I think this macro just wraps the SendMessage method, but I'm not sure. I couldn't find any C#-based samples on this.
Basically I'm trying to get a LVBKIMAGE ( http://msdn.microsoft.com/en-us/library/bb774742(v=VS.85).aspx ) structure that references the Desktop's background bitmap.
You cannot. A macro is processed at compile time by the C/C++ compiler, but you want to access the binary library. You will just have to find the macro in the source, see what it does and do the same in your C# code. It shouldn't be anything too complex. Download the Platform SDK if you don't already have it and look in the .h file mentioned in the documentation.
Edit: OK, so the macro is defined as:
#define ListView_GetBkImage(hwnd, plvbki) \
(BOOL)SNDMSG((hwnd), LVM_GETBKIMAGE, 0, (LPARAM)(plvbki))
SNDMSG is simply defined as SendMessage. LVM_GETBKIMAGE is an integer - it's 0x1045 for the ASCII version and 0x108B for the Unicode version. (You probably want the Unicode version if you're unsure.) So the entire thing resolves to:
(BOOL)SendMessage(hwnd, 0x108B, 0, plvbki)
There should be easy enough to map to C#. Look in System.Windows.Forms using Reflector to see how Microsoft have imported the SendMessage function. It will be marked internal, so you cannot call it, but you can copy it. plvbki is a pointer to a struct - you'll need to create a C# equivalent of LVBKIMAGE. Actually, MS have probably done that for you too, so look around for that.