Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ and C# interoperability : P/Invoke vs C++/CLI

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?
like image 993
prosseek Avatar asked Jun 30 '10 14:06

prosseek


People also ask

What is diff between C and C++?

Conclusion. In a nutshell, the main difference between C and C++ is that C is a procedural with no support for objects and classes whereas C++ is a combination of procedural and object-oriented programming languages.

Is C and C++ same?

C++ was developed by Bjarne Stroustrup in 1979. C does no support polymorphism, encapsulation, and inheritance which means that C does not support object oriented programming. C++ supports polymorphism, encapsulation, and inheritance because it is an object oriented programming language. C is a subset of C++.

Which is better C or C++?

Compared to C, C++ has significantly more libraries and functions to use. If you're working with complex software, C++ is a better fit because you have more libraries to rely on. Thinking practically, having knowledge of C++ is often a requirement for a variety of programming roles.


1 Answers

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.

like image 96
Kate Gregory Avatar answered Sep 30 '22 01:09

Kate Gregory