Best Design Pattern for Two-Way Data Communication in C# and C++ WinUI 3

0
0
Asked By CleverCoder123 On

I'm working on a WinUI 3 application that consists of two separate projects—one written in C# and the other in C++/WinRT. I need to establish two-way communication between the two, allowing them to pass variable data or structured objects back and forth. For instance, some data generated by the C++ project will need to be processed by the C# project, and conversely, the C# project has UI state information that the C++ project might need to access.

I'm aware of how to set up WinRT interop by designating a project as a WinRT component in the `.csproj` file, making it possible to expose public types between C# and C++ through the generated `.winmd`. My question is: what's the best design pattern to set up this communication?

I've considered using the Mediator pattern but I'm open to other suggestions. Here are my main goals: I want a clean separation between the C# and C++ code, the ability to send and receive both events and data, and to keep the architecture as straightforward as possible if there's a simpler approach. Any recommendations?

By the way, my project is open to the public on GitHub, so feel free to check it out [here](https://github.com/KrishBaidya/LlamaRun/)!

3 Answers

Answered By CPlusPlusFan1 On

Consider using C++/CLI. It adds some neat features, like access to the garbage collector, and allows certain C++ objects to behave like regular .NET objects. Another option is using RPC, but that’s usually for inter-process data sharing—might not fit if C# is solely referencing C++ here!

FocusedCoder77 -

Thanks for the suggestion, but my primary goal is to keep data passing as simple as possible. RPC feels a bit too heavy for this!

Answered By CodeNinja99 On

A straightforward way might be to use the MarshalAs attribute, although I think that's mainly for P/Invoke scenarios. Since you're working with WinRT, many types would be inherently compatible between your projects, so keep that in mind when passing data.

DataGuru88 -

I get your point, but I'm focused on a simpler data-passing mechanism here. The use cases of MarshalAs aren’t quite fitting my needs.

Answered By TechWhiz45 On

You could try using the Mediator pattern. It helps manage communication between different classes, so your C# and C++ parts can interact without being tightly coupled. It should keep things cleaner overall.

CuriousDev22 -

I gave the Mediator a shot, but it felt a bit cumbersome for this particular project. Just wanted to share my experience!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.