In the course of finding a way to interoperate between C# and C++ I found this article that explains about P/Invoke.
And I read a lot of articles claiming that C++/CLI is not exact C++ and requires some effort to modify from original C++ code.
I want to ask what would be the optimal way when I have some C++ objects (code/data) that I want to use from C# objects.
It looks like that in order to use P/Invoke, I should provide C style API. Is it true? I mean, is there a way to export C++ object to C# like SWIG with P/Invoke? Or, do I have to use SWIG for this purpose?
How hard is it to change C++ to C++/CLI? Is it worth trying compared to rewrite the C++ to C#? The C++ is well designed, so implementing it to C# is not great deal.
(Off the topic question) Is there the other way round? I mean, if I want to use C# code from C++, is there any way to do so?
I would not recommend rewritng your C++ library into C++/CLI. Instead, I would write a C++/CLI wrapper that you can call from C#. This would consist of some public ref class classes, each of which probably just manages an instance of the native class. Your C++/CLI wrapper just "include the header, link to the lib" to use the native library. Because you have written public ref class classes, your C# code just adds a .NET reference. And all you do inside each public ref class is use C++ Interop (aka It Just Works interop) to call the native code. You can apply a facade while you're at it if you like.
The C++/CLI syntax is awkward, but it does allow you to expose managed objects from C++ code. This can be convenient if you have a large C++ API and can abstract some of that functionality to a simpler interface for consumption by your managed code. I've done this successfully for integration with tools like the Matrox vision library, where I could write my vision analysis code in C++ and then use the C++/CLI extensions to expose high-level managed classes. The most painful part is probably string and array inter-op, but strings have always been painful, even in plain C++.
C++/CLI can definitely consume any .NET managed objects, but you have to take special care if you're using any pointers to managed memory (you'll need to use pinning in this case.) If I need to pass pointers to an API, I usually prefer to keep that memory unmanaged and then create managed wrapper classes for manipulating the unmanaged memory.
Further to Kate Gregory's answer, to call C# code from C++, using C++/CLI is the obvious way to do it, as it makes it extremely simple and seamless.
Wrap your C++ native classes, as pointer to implementation, into C++/CLI classes, then call & use these CLR-based classes by 'using'ing them in your .net application. This is my recommended way. DO NOT REWRITE your existing classes in C++/CLI.
Related
I have recently acquired the C++ source code of a 3D game engine I plan to use. However my C++ coding skills are far from legendary, and I definitely find C# easier to work with. I have seen components that are implemented fully in C++ and have only a set of wrapper classes in .NET, that have no source code - instead they point directly to the DLL's classes using the [ComImport] keyword to mark classes as external, and the `public virtual extern' keyword to mark functions as external. Is it possible therefore to use SWIG, create classes and methods in C# that link directly to the classes and methods in the DLL of the C++ game engine? So I should be able to instanciate the classes of the C++ engine directly in .NET, and control them from .NET. Is this possible?
You can only use [ComImport] if you C++ classes are COM objects. There is a strong possibility that they are not given this is a Game Engine. (Search your C++ code for COM methods like CoInitialize to know for sure)
Given you have the source, theoretically SWIG will create C# wrappers for your C++ , without needing you C++ classes to be COM objects, However don't expect this to be entirely trivial.
An alternative approach I've taken in the past is to write a 'C' wrapper for my C++ (google 'extern "c"') and then its easy to create C# wrappers, using pinvoke. Whether this is possible in you've case will depend on the C++ api.
Bear in mind that any C# => native (c, c++ etc) will involve some performance penalty. How much will depend on how frequent the C# -> native (or native -> C#) calls are made.
I need to write a couple DLLs that will both be accessed from a C# application and a C++ application. Initially, I was thinking that I could save time/effort by writing the DLLs in C# and linking to them from the C# and C++ applications. Is this approach wise, or should the DLLs be written using C++?
My advice would be to implement the code where you are most comfortable, but don't forget the interop requirement as you go. Know upfront what your interface is and what glue is required in the end product. Write the interface and test the interop before you fill out the implementation.
If the complexity of your requirement makes comfort level irrelevant, I would write it in C++ in such a way that you can access via P/Invoke.
One important factor is are you using C++/CLI or native C++. It's a lot easier to interop between C++/CLI and C#, in either direction.
I suggest you write your DLLs in C++, expose their public classes to COM using ATL or similar, then have tlbimp generate a thin C# wrapper around the COM interfaces.
If the DLL is to be used in other .Net applications, then you are pretty safe writing it in C# or C++, whichever you are more comfortable in.
If the DLL is to be used elsewhere, you will find it easier to write it in C++.
If you had to decide between C# and Managed C++, which would you choose and why?
Are there benefits of Managed C++ over C#? Which language do you prefer? What decisions would you make under what circumstances?
I would use managed C++ if I:
Needed to integrate with existing C/C++ code
Needed to port existing C/C++ code to .net
Needed to use .NET objects from C++
Needed to expose .NET object over COM in a more complex way than what .net makes easy
Needed to access hardware directly
Needed to call lots of unmanaged APIs
And already had some skills in C++, as the above tasks will need a experienced C++ programmer. Most of the time I would only consider managed C++ if the company already had a C++ code base, otherwise who is going to maintain the managed C++ code.
In other cases I would always choose C#. Even if I choose managed C++ for part of the system, I would try to write as much of the system as possible in C#.
Think of manage C++ as a bridge building kit for going between the
unmanaged world of C/C++ and the
managed world of .NET.
If you only need to call a few simple APIs from C#, then see pinvoke.net and this overview to find how to call them from C#, as a few lines of complex pinvoke code (prebuilt bridge) in C# is normally better then introducing C++ to a project that is not already using it.
what is the benefit of managed C++
over C#?
C++.net is useful for interacting with C++ and C code (that is, calling external C or C++ libraries, providing callback functions to external modules written in C or C++ and so on.
what language of both would you
prefer?
I would prefer C# for all situations except the one described above (interacting with C and C++).
C# is easier to write, simpler, and geared specifically to use the .NET platform. C++ can do it also, but it has all the complexity of the C++ language plus the extensions needed to use the .NET platform.
Unless you need to interact with native C++ or C code, you're better off using C# in most cases (that is, if you're coding for the .NET platform).
Normally I prefer C++, but when needing to code for .NET, it doesn't beat C#.
Managed C++ is good for interop with C++: for example, if you have a .NET application and your assembly has to interact with a native interface that comes as C++ .lib files (which I had more than once), or with a nice C++ API.
Example: Rithmic (not that you ever heard of them) until recently ONLY supported a C++ API. If you try to access them from C# - good luck ;) Managed C++ allows me to access their API and expose nice .NET objects.
Basically interop. Managed C++ REALLY shines in interop with low level C / C++ API's.
I used managed C++ when I needed to build up new NET component with much ofC++ unmanaged code inside.
I did a specific class used to Marshall some objects forward and back from old C++ code.
I've encountered a problem which was transparent in managed C++, but made a big headache in C# - I had to send a callback function to a C++ unmanaged library, that defined this callback as __cdecl. In C#, the default calling convention is __stdcall, and it is pretty compilcated to move a C# delegate from __stdcall to __cdecl (Actually it requires either a 'shim' unmanaged DLL to do so or using some reflection classes).
In C++, (C++.Net as well), it is just a simple attribute.
I haven't personally written, or read for that matter, too many lines of code in managed C++, but from what I have seen it looks too convoluted and patchy. That said, you might want to use managed C++ if you are really good in C++, and when learning the idioms and patterns of a new language would be too much of a risk.
Use C# if you are quite competent in it. If you are only getting started with C++ and C#, I think, C# is the easier route to take.
I would prefer C#, or specifically .NET, over C++ because of the extensive .NET standard library.
I need to access code in a native C++ DLL in some C# code but am having issues figuring out the marshaling. I've done this before with code that was straight C, but seem to have found that it's not directly possible with C++ classes. Made even more complicated by the fact that many of the classes contain virtual or inline functions. I even tried passing the headers through the PInvoke Interop Assistant, but it would choke on just about everything and not really no what to do... I'm guessing because it's not really supported.
So how, if at all possible, can you use a native C++ class DLL from .NET code.
If I have to use some intermediary (CLR C++?) that's fine.
There is really no easy way to do this in C# - I'd recommend making a simple wrapper layer in C++/CLI that exposes the C++ classes as .NET classes.
It is possible to use P/Invoke and lots of cleverness to call C++ virtual methods, but I wouldn't go this route unless you really had no other choice.
You might have a look at SWIG, if nothing else just to see how they handle the basic wrapper code (which SWIG generates). I know next to nothing about C# native code bindings so I can't judge if their approach is sound, but they do a decent job with some of the other language bindings.
I have a native C++ DLL using DirectX, that I want to be able to use through C# to be able to create content creation tools.
Adding COM would require quite an effort it seems.
Can P/Invoke be used to maintain classes using polymorphism, or would it require me to wrap most of the code to facilitate use of P/Invoke?
It there a better solution is available? Or should I even consider writing the tools in C++ using Qt perhaps?
I always feel that C++/CLI is always the best option when doing C# to C++ interop. You can easily create thin wrappers for an unmanaged library that will look exactly like a managed library to your C# code. It also gives you more control over how marshaling and pinning is performed.
There are ways to automatically generate C++/CLI I believe, but I've never used them.
More info on C++/CLI here:
http://msdn.microsoft.com/en-us/magazine/cc163681.aspx
I presume rendering with D3D directly from C# isn't an option? (because that certainly would be easier!)
A long time ago, I used SWIG to automatically maintain C# "bindings" of my C++ rendering DLL code. It uses P/Invoke to expose the C++ objects on the C# side, and you won't have to maintain that code anymore.
You don't need to write wrap on QT.
I advice you to write Observer class both in C# & C++, and hide calls of Native functions to it.
Schema is like this
Your code in C# -> Observer(C#) -> Native call to Observer(C++) -> Calls to your dll.