C# – Communication between a C# application and C++ DLL

cdllwpf

I am currently building an audio streamer and I have a CPP .dll that I use functions of inside the WPF C# GUI.

The program needs to deal with sorts of events such as

  • Lower/Increase Volume
  • Manipulate Equalizer Bands

To this point I have used named events to deal with this issue. What would be a better way of handling all those events from the GUI to the .dll? The events system I use (.dll spawns a thread which while-s on a WaitForMultipleObjects), or would it be better/smarter/more-beneficial or just better-practice to use a named pipe instead?

Best Answer

You can call from C# to C/C++ directly using a technology known as P/Invoke. With P/Invoke, a C++ function can be made to look just like a C# function.

Here's a simple example from this article in MSDN Magazine:

C Method Definition

BOOL MessageBeep(
  UINT uType   // beep type
);

P/Invoke Definition in C# of method in C

[DllImport("User32.dll")]
static extern Boolean MessageBeep(UInt32 beepType);

Calling the C method from C#

MessageBeep(0);

Now, isn't that simple & clean? Much of the .NET Base Class Library is implemented as C/C++ code with a P/Invoke wrapper and a C# facade. The .NET team itself uses P/Invoke rather than COM for this type of interop, it's simpler and more efficient.

A great resource for finding how to write P/Invoke method definitions is pinvoke.net.

Related Topic