Call C++ code from a C# application or port it? - c#

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.

Related

Integrating Matlab Coder with c#

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)

LSODA to dll - Fortran (F77) to dll to call from C#

a little question in which I hope you can help me. (To make my life simpler)
One of the most respected numerical solvers for differential equations is LSODA, however it is written in Fortran... ( http://www.netlib.org/odepack/index.html )
There does not seem to be a decent solver for C#, and writing my own is too time consuming in C#, especially as I have very stiff equations that need to be solved.
The NAG libraries for net do not contain an ODE solver (they lack D02 routines). In terms of "university side" libraries that's it.
However NAG Support suggested calling their dll, which is fine for simple variables, but has me rather perplexed with its external functions and dummy parameters which made me give up.
This leaves LSODA still, which is fortran, but a lot simpler in its calling sequence - so I wonder, how can the Odepack (the solvers that include the lsoda routine) be turned into a dll with little work, so that it may be called from C#?
(Which will leave me worried about the Jacobian, being a matrix, i.e. 2D array.)
Specifically, I would like a situation similar to that with the Fortran NAG library, but instead offering me access to lsoda: http://www.nag.co.uk/numeric/csharpinfo.asp
Please keep in mind that I am a mathematician - so if your responses loose me, please be patient with me. And why am I so focused on C# - well, it is simple, especially when one has VisualStudio 2010.
Many thanks for any responses in advance.
SmartMathLibrary looks dead, but it claims to have ODEPACK bindings. You could also check out Wikipedia's List of .NET Numerical Packages.
If you're open to other languages, Python's SciPy library contains a binding to LSODA: enter link description here. It's available on Windows, easy to use, free, and widely embraced by the scientific community.
It's not a full solution, but f2c (Fortran-to-C converter) should be able to give you working C code from the Fortran source. That might at least be easier to get working from C#.
Disclaimer: I've never used f2c to convert a routine, I've only used some of the routines that someone else converted.

Is there a tool to convert ANSI C code to C#?

I need to import some ANSI C code into a project I'm working on. For reasons I prefer not to go into, I want to refactor the code to C# rather than trying to wrap the original code. It will take me perhaps a couple of days to do the work by hand, but before I start, is there an automated tool that can get me most of the way there? I'm a cheapskate and the work I'm doing is pro bono, so free tools only please.
If manual refactoring is "only" going to take a few days, that would get my vote. Depending on what the C code is doing and how it is written (pointers, custom libraries, etc.) an automated converter may just make a mess. And untangling that mess could be a larger task than just converting by hand.
Setting up, cleaning up, refactoring, and just plain making converted code (if there is even a converter available) would probably be something in the magnitude of weeks or months, so you'll be better served just to go ahead with the manual rewrite.
There is an experimental CLI Back-End and Front-End for GCC. It is already capable of compiling a subset of C programs into CIL, the byte-code that the CLR runs.
(The webpage makes it seem like the code was only developed over a few months and then ignored since then, but it's out of date; ST Microelectronics is continuing maintenance and development.)
You don't specify why you want a C to C# translator, but if you just want to get C and C# to play together without P/Invoke or COM, it might be good enough.
It may make sense to start by getting the existing code to compile as managed C++ aka C++/CLI. Assuming that went smoothly enough, then you have a working, testable foundation on which to build. Move key features to their own classes, and as needed, rewrite as C# along the way.

Use C++ class from C#

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.

Turning C# methods into C++ methods

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.

Categories

Resources