I have inherited a large C++ codebase implementing various Windows desktop applications, services and libraries using Windows MFC. There are no automated tests. We need to decouple the UI and retain a large part of the domain logic written in C++. My understanding is I can implement high-level use cases in C++ and expose these use cases as functions in a C interface. This interface would take or return structs as payloads, much like a REST API would accept or return JSON.
This design would then allow me to call into the legacy code using a high-level API with a more Ui-friendly language like C# or Javascript. It would provide a clean API to introduce automated tests and would also allow me to migrate the logic and services to the web if required.
Is this approach in line with modern C++ software architecture? Is a C interface the best choice in this scenario? What risks should I be aware of?
1 Answer 1
Yes, do it. This is a surprisingly common problem, and I just finished doing one.
The choice of a C API is a good one, and designing this is really the only hard part. Take it seriously! Just a few thoughts:
- simple data types: ints, floats, structs (but no pointers)
- a consistent strategy for variable sized items: strings and arrays
- prefer command/query
- be very consistent in naming and usage
- make sure it's easy and natural to call in C# and Python (then the rest are easy)
- prefer unit tests in C#
- probably need 64-bit (if it wasn't already)
Avoid C++/CLI -- it's a quick fix, but you will regret it over time.
-
C++/CLI is not a quick fix. Having several years of experience with that technology, I know first hand that your last sentence is simply biased nonsense.Doc Brown– Doc Brown2022年02月04日 13:36:17 +00:00Commented Feb 4, 2022 at 13:36
-
"prefer command/query". As opposed to...? Passing in handles? Why would I regret C++/CLI?DLT– DLT2022年02月04日 21:54:33 +00:00Commented Feb 4, 2022 at 21:54
-
@DocBrown: C++/CLI is superb technology as long as you are totally committed to a Microsoft environment. Not so great if you later need Linux, mono, Unity, etc.david.pfx– david.pfx2022年05月08日 01:38:12 +00:00Commented May 8, 2022 at 1:38
-
@DLT: CQS rather than API calls that both change state and return a value (like much of Windows). Use handles (rather than than pointers) as a choice in how to manage state. This is a topic for a book, not a brief comment.david.pfx– david.pfx2022年05月08日 01:44:27 +00:00Commented May 8, 2022 at 1:44
Explore related questions
See similar questions with these tags.
[DLLImport("TheCPPLib.dll")]
so you can directly call the c++ code from c#. Shouldn't be a need for a C wrapper, right? I haven't tried this, so I'm not sure.