Consuming a C++ DLL in dotnet core

View Reddit by KenBonnyView Source

Categories: C#


Slypenslyde · September 14, 2020 at 1:05 pm

Learning how to PInvoke is one of those skills that doesn’t take too much time on the side to learn, but will make people who are scared of it think you are a wizard.

unique_ptr · September 14, 2020 at 2:12 pm

>The most simple solution to this problem is to convert the console app to a WinForms app and call Application.DoEvents() in the while loop in the CustomApplicationIntegration class.

Ahhh! I just ran into a similar problem the other day while working on a (better) managed wrapper for SimConnect–it also requires creating a Win32 message pump and I was also in a console application. The “simple” solution I found was to subclass `NativeWindow` from `System.Windows.Forms` as it will provide a managed version of a native window handle complete with a `WndProc` method for hooking into messages, like so:

class SimConnectNativeMessageHandler : NativeWindow, IDisposable
public SimConnectNativeMessageHandler()

protected override void WndProc(ref Message m)
// Handle message m

base.WndProc(ref m);

// Call DestroyHandle() in IDisposable implementation

Then in your Main() (or wherever) you create an instance and call `System.Windows.Forms.Application.Run()`. I don’t know that it’s a *better* solution than a `while` loop calling `Application.DoEvents()`, but it does what it needs to.

Not wanting to take a dependency on `System.Windows.Forms` and having enough Win32 experience to have some semblance of an idea of what I was doing, I did attempt a pure P/Invoke solution but after a couple of hours threw in the towel knowing I had bigger fish to fry. If anyone’s got a good example of creating a simple, message-only window with P/Invoke I’d be very interested to take a look at it.

Leave a Reply

Your email address will not be published. Required fields are marked *