3

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?

5
  • Interop? .. . . Jan 25, 2013 at 0:07
  • 1
    If you are ok being beholden to Windows platform COM would probably be the way to go. Jan 25, 2013 at 6:16
  • 1
    @whatsisname: You don't need COM. You can call DLL's with C calling convention from C#. Jan 25, 2013 at 20:36
  • 1
    @RobertHarvey: that is true, but you have the hassle of creating a C wrapper API around your objects. While COM isn't hassle free either, it can provide a better C# <-> C++ interface for objects. Feb 7, 2013 at 0:49
  • If they live in different OS processes, named pipe is indeed a suitable choice.
    – rwong
    Apr 3, 2013 at 2:56

1 Answer 1

6

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.

1
  • 1
    This only works well if the API only exhibits C types. Using an API that exhibits C++ types that way is problematic. Mar 3, 2013 at 15:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.