Can I call C ++ code from C #?

Is it possible to call C ++ code, possibly compiled as a code library (DLL) file, from a .NET language such as C #?

In particular, C ++ code, such as the RakNet network library.

+71
c ++ c # managed unmanaged
Jun 01 '09 at 16:46
source share
7 answers

One easy way to call in C ++ is to create a wrapper assembly in C ++ / CLI. In C ++ / CLI, you can call unmanaged code as if you were writing your own code, but you can call C ++ / CLI code from C #, as if it were written in C #. The language was mainly developed with interop in existing libraries as a killer application.

For example - compile this with the / clr switch

#include "NativeType.h" public ref class ManagedType { NativeType* NativePtr; public: ManagedType() : NativePtr(new NativeType()) {} ~ManagedType() { delete NativePtr; } void ManagedMethod() { NativePtr->NativeMethod(); } }; 

Then in C # add a link to your ManagedType assembly and use it like this:

 ManagedType mt = new ManagedType(); mt.ManagedMethod(); 

Let's open this blog post for a more explained example.

+76
Jun 01 '09 at 16:56
source share

I am not familiar with the library you mentioned, but overall there are several ways to do this:

  • P / Invoke for exported library functions
  • Adding a reference to a library like COM (in case you are dealing with COM objects).
+7
Jun 01 '09 at 16:50
source share

P / Invoke is a good technology, and it works quite well, with the exception of problems loading the target DLL file. We found that the best way to do this is to create a static library of your own functions and link it to a C ++ (or C ++ / CLI) managed project, which depends on it.

+7
Jun 01 '09 at 16:55
source share

Yes, it's called P / Invoke .

Here's a great resource site for use with the Win32 API:

http://www.pinvoke.net/

+3
Jun 01 '09 at 16:54
source share

Sure. This article is a good example of what you can do to get you started.

We do this with C # on our Windows Mobile devices using P / Invoke .

+1
Jun 01 '09 at 16:49
source share

The technology used to do this is called P / Invoke ; You can search for articles on this subject. Note that this is for calling C from C #, not C ++. Thus, you need to wrap your C ++ code in the C wrapper that your DLL exports.

+1
Jun 01 '09 at 16:51
source share

Did you consider Apache Thrift?

http://thrift.apache.org/

This seems to be a very clear solution.

-one
Nov 25 '10 at 19:39
source share



All Articles