I want to integrate MATLAB Coder output with a C# project in Visual Studio 2010. My main idea is:
Create a *.m script in Matlab
Make sure the script is compatible with Matlab Coder.
Generate a C++ shared library (DLL) with Matlab Coder
Integrate with C# using something like this:
//Starts the model execution. May take several minutes
public static class DllHelper
{
[DllImport(#"test.dll",CallingConvention=CallingConvention.Cdecl,EntryPoint = "Run()")]
public static extern int Run();
}
Also, I would like to be able to stop the execution and retrieve some partial results. To do this, I was thinking in two methods: StopExecution and RetrievePartialResults
[DllImport(#"test.dll",CallingConvention=CallingConvention.Cdecl,EntryPoint = "StopExecution ()")]
public static extern int StopExecution ();
[DllImport(#"test.dll",CallingConvention=CallingConvention.Cdecl,EntryPoint = "RetrievePartialResults()")]
public static extern MyResults RetrievePartialResults();
Is it possible to do? If no, is there any alternatives? If yes, where can I find more examples?
I have no idea if your plan works, but MATLAB Builder NE might be an alternative. It directly outputs a .Net dll without those hard limitations to the m-code.
The disadvantage is, that MCR is required on the target machine.
I've done both ways. Formerly, our project was using MATLAB Compiler, but we now switched to Coder, because that avoids the overhead of having to install the runtime (which btw often failed to start inside the process for no apparent reason).
We compile the coder output as an unmanaged C project with a C interface and use a C++/CLR project as a wrapper. This has the advantage that we don't need to manually specify the interface for P/Invoke as the compiler will directly read the header files. The C++/CLR assembly is the linked to the C# project where the code is going to be used. Be aware that this is kind of expensive, so try to avoid calling the matlab code in a tight loop and better move the whole loop into the library if that is possible.
Here's a snippet from the wrapper library (still uses old Managed C++ syntax, but that doesn't matter here)
bool CTurconConnect2::Init()
{
// Call the exported function in the library. Imported using a header file.
turcon_initialize();
// Call one of the matlab functions (in this case, the entry function is manually defined
// in the C library, to have a clean interface)
SetParameters(36.0,400.0,20.0,30.0,15.0,40.0,110.0, 0.0, 100.0);
return true;
}
bool CTurconConnect2::Exit()
{
turcon_terminate();
return true;
}
I think your plan of writing a DLL and calling it from c# seems to be one of the two main ways to go.
The alternative would be to:
use the MATLAB as an automation server from C# using the engine
interface via com automation. This allows you to simultaneously debug
your C# application from both the C# side and the MATLAB side, using
debuggers on each side.
Here are examples for both methods, and even a third alternate method (that seems less recommended).
Integrating MATLAB with C# on File Exchange
I've achieved the exact functionality you're asking about using the MATLAB Compiler. I don't have any experience with the MATLAB Coder, but should be the same principle. Once you have a MATLAB Library compiled, you can access it using P/Invoke in C# like you would with any other unmanaged library (and as you specified in your question).
Theres a couple of caveats:
I think you might have an issue design-wise trying to successfully implement your "stop execution" strategy. The MATLAB executables/libraries are meant to execute from start to finish without much control over the runtime. If you can split your script up into multiple pieces to handle that design, that may work better.
Compiled MATLAB libraries require you to "Start" and "Stop" the MATLAB Component Runtime manually, as well as a component runtime for each script. So, execution flow, would be something like:
StartMCL();
StartScript1_Runtime();
Run_Script1();
StopScript1_Runtime();
StopMCL();
If you attempt to run the "Script 1 Runtime" prior to starting the overall MCL, the app will crash. So, you need to be careful with how you design the wrapper class to handle that properly. Also, you want to be sure to Stop everything before exiting your app, otherwise, the MCR will effectively see 2 "Runs" in a row, and will crash.
You didn't cover any input/output arguments in your question, but in most cases, you will need to use MATLAB functions to create the MEX variables to hand data in/out of the MATLAB environment.
There is a great set of sample source here that should cover all of the above:
http://www.mathworks.com/matlabcentral/fileexchange/12987-integrating-matlab-with-c
Also, the Compiler help itself has a bunch of useful resources.
http://www.mathworks.com/help/compiler/shared-libraries.html
So in a list form,
I doubt that you will be able to stop the matlab code unless you break it up into multiple functions, which you may call as needed.
That you should be able to halt execution by calling on a thread and stopping the thread as you need, or better, send a signal for the thread to stop, which it will abort between functions (for the purpose of partial results)
That matlab is a terrible language for fulfilling the requirements on item 1 (not that I have ever had any good experiences with it myself)
Related
I know this is wrong (trying to code in C# with a C/C++ mindset).
But is it possible to create inline functions / inline recursive functions (til the Nth call) / macros in C#?
Because if I intend to call the same function 1000 times, but it's a simple function, the overhead of creating the stack is quite big... And unnecessary.
In C i could use inline functions. Is there something like that in C#?
Again... I'm not saying that C/C++ is better... I'm just new to C# and have none to ask those simple questions...
Inline functions in C#?
Finally in .NET 4.5, the CLR allows one to force1 method inlining
using MethodImplOptions.AggressiveInlining value. It is also available
in the Mono's trunk (committed today).
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
void Func()
{
Console.WriteLine("Hello Inline");
}
The answer should be: don't worry about it. No need to start with micro-optimizations unless you've tested it and it's actually a problem. 1000 function calls is nothing until it's something. This is majorly overshadowed by a single network call. Write your program. Check the performance against the goals. If it's not performant enough, use a profiler and figure out where your problem spots are.
Yes, C# is a very powerful general purpose language that can do nearly anything. While, inline functions / macros are generally frowned upon, C# does provide you with multiple tools that can accomplish this in a more concise and precise fashion. For example, you may consider using template files which can be used (and reused) in nearly all forms of .NET applications (web, desktop, console, etc).
http://msdn.microsoft.com/en-us/data/gg558520.aspx
From the article:
What Can T4 Templates Do For Me?
By combining literal text, imperative code, and processing directives, you can transform data in your environment into buildable artifacts for your project. For example, inside a template you might write some C# or Visual Basic code to call a web service or open an Excel spreadsheet. You can use the information you retrieve from those data sources to generate code for business rules, data validation logic, or data transfer objects. The generated code is available when you compile your application.
If you're new to programming I would recommend against implementing templates. They are not easy to debug in an N-Tier application because they get generated and ran at run-time. However, it is an interesting read and opens up many possibilities.
I am attempting to connect to a commercial server application, which only has a C# API.
I would imagine that the best approach for doing so would be to create a C# DLL - which is what I have done. However, when examining the methods contained within the DLL utilising 3rd party tools, the methods do not seem to be visible.
I have searched extensively on StackOverflow, and found that the following suggestion works for most people - however the methods are still not visible when utilising this extension.
Thus it may be time to seek an alternate approach to how this problem can be solved - one option could be a C# console application.
Any ideas regarding what would be the best approach?
EDIT:
After running the DUMPBIN program, this is the output:
C:\Program Files (x86)\Microsoft Visual Studio 11.0>dumpbin /EXPORTS "C:\Users\mark\Desktop\Test.dll"
Dump of file C:\Users\mark\Desktop\Test.dll
File Type: DLL
Summary
2000 .reloc
2000 .rsrc
2000 .text
If the Basic+ has an option to call C code, you have an option to create a project in Managed C++:
Exports some function decorated like:
extern "C"{
__declspec(dllexport) void _cdecl MyFunction()
{
_MyImpl(); //see below wy this
}
}
void MyImpl()
{
MyCSharpObj^ test = gcnew MyCSharpObj()...
test->Methods(...
}
Outside of the portion decorated with extern C you can safely call and mix managed and unmanaged calls. The reason you should go outside the extern C block is that almost all managed function have overloads, and Extern C does not support method overloading even in call.
You can call c# by just adding references ( actually you can write all your code in managed C++, but is not so friendly ) to your .NET libraries.
Basic+ seems to be made by Revelation Software.
On this page, it says:
OpenInsight 9.1 released
This new OpenInsight release included a
couple of .NET innovations. NetOI enables developers to code using
their Microsoft Visual Studio licenses and work against an OpenInsight
database. The RevDotNet functionality provides a method of calling
.NET APIs and using the .NET controls within an OpenInsight
application.
Can you use RevDotNet to call your C# APIs directly?
Alright so I have this C++ image capturing class. I was wondering if I could get some help..I know basic C++ (I have done one intro to c and one intro to c++ class) and I have NO idea how to do this:
I need to use this class (ie create a new c++ project in my solution) and use c# to reference it and use it to save a screenshot of the screen.
When I try to add a new project I dont know which one to choose (win32, mfc, atl, clr, abc, xyz, and so on) .
The image capturing class is here:
http://pastebin.com/m72414ab
I don't know if I need to create .h files or just a .cpp file would do.. like honestly I have no clue where to start lol. I am looking for a solution, but i want to learn in the process so I dont have to ask next time (not to mention that I like c++ so I am gonna continue coding with it)
You cannot easily use C++ classes from C# without knowing some somewhat specialized information about C++/CLI - either rewrite your C++ class in C and use P/Invoke, or find a fully C# solution.
But I'd like to use this c++ class for speed and memory.
I question this, unless you are capturing images thousands of times a second, there's no way choosing C++ would be of any benefit, and it makes your program much more complicated. Stick with C# until you know you need the slight performance boost.
.NET version 2.0 and above include a CopyFromScreen method on the Graphics object. You can create an image, obtain a drawing surface (Graphics) for that, and then copy from the screen into the image.
A quick bit of Googling produced a simple tutorial which demonstrates this using Visual Basic .NET, although it's trivial to port to C#.
This solution results in the same GDI+ calls that your C++ version uses, with the benefit of not having to link in external C++ code (which, as mentioned above, is not straightforward).
It is definitely possible to use C++ constructs from C#, but it does require some dirty tricks. If I remember correctly, last time I tried to do this I used a Managed C++ layer between C++ and C#, and I think this is the most common way to do it. This method worked well, but indeed was unnecessarily complicated.
I've recently been wrestling with an algorithm which was badly implemented (i.e. the developer was pulled off onto another project and failed to adequately document what he'd done) in C#.
I've found an alternative (from numerical recipes) which works but is written in C++. So I'm thinking probably the safest way to get something working would be to wrap the C++ up in a DLL.
Bearing in mind that I'm still a bit green when it comes to C# and have never tried making a DLL from scratch, does this sound like a reasonable approach (and if so, has anyone tried this / got any advice)? Or should I go the whole hog and try and port the C++ routine into C#?
Edit - I'm not looking for anyone to make the decision for me, but if anyone has any exprience of either route I'd be interested to hear their opinions and any nasty pitfalls that should be avoided. For example, how nasty is passing in lists of data from C# to a C++ STL vector?
I tried linking to c-dll's from c# code with quite good results, even though I had some problems sending data between the environments. Otherwise the procedure is quite straight forward. The more data you send back and forth (both amount and frequency) the slower your program will run, but you have probably already figured this out on your own.
The main drawback was maintaining the c#-c glue code (interface code) each time something changed or someone found a bug.
Here is a bit of code to get you started:
using System.Runtime.InteropServices;
class myDllCaller {
//call to function in the dll returning an int
[DllImport("MyFavorite.dll")]
private static extern int dllFunction(//list of parameters to function);
public static void Main() {
int rerult = dllFunction();
}
}
If the C# version Mitch references isn't of a suitable licence for your purposes, You could use a managed C++ wrapper, that could reuse, and wrap the C code you have, but still be visible to your managed applications as a native .Net assembly. I've used this approach in the past for using the C API of a library that didn't have its own native .Net API, and found it relatively painless marshalling data between the two.
It depends what your goals are.
If it's to have a working application I'd weigh-up the costs and benefits of both approaches and go with the most cost effective.
If it's to improve your C# then by all means rewrite the C.
...Or you could download the already implemented code in C# from here.
I'm exploring various options for mapping common C# code constructs to C++ CUDA code for running on a GPU. The structure of the system is as follows (arrows represent method calls):
C# program -> C# GPU lib -> C++ CUDA implementation lib
A method in the GPU library could look something like this:
public static void Map<T>(this ICollection<T> c, Func<T,T> f)
{
//Call 'f' on each element of 'c'
}
This is an extension method to ICollection<> types which runs a function on each element. However, what I would like it to do is to call the C++ library and make it run the methods on the GPU. This would require the function to be, somehow, translated into C++ code. Is this possible?
To elaborate, if the user of my library executes a method (in C#) with some arbitrary code in it, I would like to translate this code into the C++ equivelant such that I can run it on CUDA. I have the feeling that there are no easy way to do this but I would like to know if there are any way to do it or to achieve some of the same effect.
One thing I was wondering about is capturing the function to translate in an Expression and use this to map it to a C++ equivelant. Anyone has any experience with this?
There's CUDA.Net if you want some reference how C# can be run on GPU.
To be honest, I'm not sure I fully understand what you are getting at. However, you may be interested in this project which converts .Net applications / libraries into straight C++ w/o any .Net framework required. http://www.codeplex.com/crossnet
I would recommend the following process to accelerate some of your computation using CUDA from a C# program:
First, create an unmanaged C++ library that you P/Invoke for the functions you want to accelerate. This will restrict you more or less to the data types you can easily work with in CUDA.
Integrate your unmanaged library with your C# application. If you're doing things correctly, you should already notice some kind of speed up. If not, you should probably give up.
Replace the C++ functions inside your library (without changing its interface) to perform the computations on the GPU with CUDA kernels.
Interesting question. I'm not very expert at C#, but I think an ICollection is a container of objects. If each element of c was, say, a pixel, you'd have to do a lot of marshalling to convert that into a buffer of bytes or floats that CUDA could use. I suspect that would slow everything down enough to negate the advantage of doing anything on the gpu.
What you could do would be to write an own IQueryable LINQ provider, as is done for LINQ to SQL to translate LINQ queries to SQL.
However, one problem that I see with this approach is the fact that LINQ queries are usually evaluated lazily. In order to benefit from pipelining, this is probably not a viable solution.
It might also be worth investigating how to implement Google’s MapReduce API for C# and CUDA and then use an approach similar to PyCuda to ship the logic to the GPU. In that context, it might also be useful to take a look at the already existing MapReduce implementation in CUDA.
That's a very interesting question and I have no idea how to do this.
However, the Brahma library seems to do something very similar. You can define functions using LINQ which are then compiled to GLSL shaders to run efficiently on a GPU. Have a look at their code and in particular the Game of Life sample.