I had working code that implemented a wrapper and interface along the lines of:
public class wrapper : wrapperInterface {
...
}
Intellisense was generating a wrapperInterfacePtr so that in a C++ header I had a valid statement of:
wrapper::wrapperInterfacePtr m_wrapper;
I was mucking around trying to add some Delegate functionality so I could pass a C++ callback into the C# (I failed), and at some point during the mucking around the auto-generated wrapperInterfacePtr became undefined. Even after I returned all the code to (what appears) to be its original state, Intellisense is not generating wrapperInterfacePtr.
Any thoughts on how what I could have done, or how to kick-start Intellisense?
Ok, I got it to work again. I can't give the definitive reason it failed, but I have an idea. The new c# managed code is on top of a huge library of existing C++ unmanaged code. I build the managed code using VS and then use an in-house tool to build everything else. The in-house build tool doesn't do a clean unless you really, really force the issue. (It would take days.) When I did a build-clean on the dlls that interfaced with the managed code, that fixed the problem.
Related
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)
How I can translate small C++/CLI project to c#
One roundabout, manual way would be to compile your C++/CLI project and open the output assembly in Reflector. Disassemble each class, have it convert the disassembled IL to C#, and save that code off.
As for an automatic way to do it, I can't think of any off the top of my head.
Those things being said, are you sure you really want to convert your project to C#? If your C++/CLI project uses any unmanaged code, you'll have a difficult time coming up with a purely managed equivalent. If the project is more or less composed of pure CLR code, and it was written in C++/CLI for the sake of being written in C++/CLI, I can understand wanting to convert it to C#. But if there was a reason for writing it in C++/CLI, you may want to keep it that way.
IMHO, line by line is the best way. I've ported several C++ style projects to a managed language and I've tried various approaches; translators, line by line, scripting, etc ... Over time I've found the most effective way is to do it line by line even though it seems like the slowest way at first.
Too much is lost in a translator. No translator is perfect and you end up spending a lot of time fixing up the translated code. Also, translated code as a rule is ugly and tends to be less readable than hand crafted code. So the result is a fixed up, not very pretty code base.
A couple of tips I have on line by line
Start by defining all of the leaf types
For every type that has a non-trivial (freeing memory) destructor, implement IDisposable
Turn on the FxCop rule that checks for lack of Dispose calls to catch all of the places use used stack based RAII and missed it
Pay very close attention to the uses of byref in C++.
I haven't tried it, but I just googled it and found this: http://code2code.net/
According t it, you shouldn't fully rely on the code it produces:
You accept that this page does only half the work.
Futher work on your part is required. In most cases, the translated code will not even compile.
Also, read this: Translate C++/CLI 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.
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.