C# – Integrate C++ DLL with C# GUI asynchronously (design issue)

cdllreal timeuser interface

This is more a design than an implementation question. I am aware of how to integrate a C++ DLL within a C# main app that acts as GUI. Believe me that I've read all other questions on similar topics, but none of them clearly answer my question, so here we go:

  • I have a C++ DLL with a few functions that interact with an API to another system (black box for me). The function that connects to the API must be "alive" whilst the whole program is running, otherwise connection to the API is lost and everything becomes more difficult. So, bare in mind that if I call the "Connect" function in the DLL and then I return to C# code, the DLL code will be out of context (no longer under execution), and disconnection will occur (correct me if I'm wrong please).

  • So far it seems that what I need is:

    a) Call the C++ DLL functions using P/Invoke as usual

    b) Design a mechanism that keeps the DLL function (including calls to other functions within the DLL running all the time)

    c) Each time the C++ DLL module has new fresh data, callback the C# and update all necessary data for presentation.

It seems easy, but I don't manage to make the design in a way that none of them gets stuck. I've tried using infinite loops in the C++ DLL side, but then the GUI gets stuck. If I just perform a call to the DLL every "x" seconds, then I'm polling too many unnecessary times and the GUI becomes slow and not elegant in the refreshing. Besides, having the GUI as the "master" and the DLL as the "slave" results in disconnections because of DLL stopping execution whilst in C# code context.

Don't be too hard with me guys, I know there must be some simple design issue that I am not considering, but I can't find out what is it. I am new on C#, not on C++.

Also, I would appreciate if you could suggest another solution for a case where refreshing data from the DLL side would be almost real time, just like reading instant speed of a vehicle in real time.

Best Answer

a) Call the C++ DLL functions using P/Invoke as usual

This indicates that the OP did not read all there is.

P/Invoke is fine as it goes, but for more complex scenarios, a C++/CLI layer is far more appropriate, especially when it comes to callbacks into .NET.

The rest of the question IMHO cannot be answered without further detail from the OP, so I'll leave it at that.