views:

2756

answers:

7

Hi, is it possible to call C++ code, possibly compiled as a code library file (.dll), from within a .NET language such as C#?

Specifically, C++ code such as the RakNet networking library

Would really appreciate it if anyone could give me some pointers on how to do this/point me in the general direction to get started doing this and I can do the further reading up on my own :)

Thanks!

A: 

Sure is. This article is a good example of something you can do to get started on this.

We do this from C# on our windows mobile devices using PInvoke.

Mat Nadrofsky
+4  A: 

I'm not familiar with the library you mentioned, but in general there are a couple ways to do so:

  • P/Invoke to exported library functions
  • Adding a reference to the COM type library (in case you're dealing with COM objects).
Mehrdad Afshari
A: 

The technology used to do this is called "PInvoke", you can search for articles on the subject. Note that it is for calling C from C#, not C++ so much. So you'll need to wrap your C++ code in a C wrapper that your DLL exports.

Frank Schwieterman
A: 

Yes, it is called P/Invoke.

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

http://www.pinvoke.net/

Dana Holt
+3  A: 

P/Invoke is a nice technology and it works fairly well, except for issues in loading the target dll. We've found that the best way to do things is to create a static library of native functions and link that into a Managed C++ (or C++/CLI) project that depends upon it.

plinth
I've had issues with callbacks and p/invoke. Switching over to C++ / CLI has addressed these issues.
MedicineMan
+4  A: 

One easy way to call into is to create a wrapper assembly in C++/CLI. In C++/CLI you can call into unmanaged code as if you were writing native code, but you can call into C++/CLI code from C# as if it were written in C#. The language was basically designed with interop into existing libraries as its "killer app".

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 reference to your ManagedType assembly, and use it like so:

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

Check out this blog post for a more explained example.

Eclipse
A: 

You can write a P/Invoke signature for each function you want to use.

You can use SWIG to generate P/Invoke signatures.

Or you can use managed c++ to call the wrapper and compile the managed c++ into a managed DLL and then add it as a reference.

Or you can use IJW in managed code - look into this one it might be the simplest, http://www.codeproject.com/KB/mcpp/nishijw01.aspx

You cannot call static libraries (.lib), only dynamic (.dll) from managed code via P/Invoke.

iterationx