13

I have a class library written in C#, and I want to call it from a legacy native C++ application. The host application is truly native, compiled on Windows and Linux, and it’s a console application. So how can I make it call the C# class library, assuming using Microsoft .NET on Windows, and Mono on Linux?

I have looked at SWIG and wrapping with COM interfaces on Windows, but is there a standard recognized solution that works cross platform? I.e., that is generic, works with both Microsoft .NET and Mono. A write-once-use-everywhere implementation.

Solutions should expose the full class interfaces from the C# domain to the C++ domain.

Similar questions focus only on the Windows solutions, for example -

Call C# methods from C++ without using COM

1
  • You'd have to ask the mono guys if, and how, they have exported that. Commented Aug 22, 2009 at 0:39

2 Answers 2

7

If you want to do this cross platform, I would recommend going with a 100% Mono approach.

Mono has a clean Embedding API which works on Linux and Windows.

Sign up to request clarification or add additional context in comments.

2 Comments

Good answer, embedding Mono on Windows not really what I was looking for also it all looks very manual. You would have to write a lot of boiler plate code to expose an full interface to a library, it looks time consuming and fragile, reminds me of JNI. I was wondering if there is some sort of automated way, like SWIG or just exposing a COM interface.
COM works well, but not so well on linux. SWIG is only good for going the other way... Sorry.
3

With .NET 5.0 (the successor of .NET Core) this is now possible to call C# from C++ in a cross-platform way without using Mono. Please see the solution explained in this GitHub issue using DNNE to generate a shared library and GCHandles to access C# objects.

With this you get a shared library that can be used from C or C++. Note that this will give a C-like API (no objects, like when using extern C in C++), in the future there may be tools like SWIG for C++ to overcome this limitation.

4 Comments

Please post the code inline. If not possible, please link directly to the code snippet instead of a github issue containing multiple comments.
@Gili here is a snippet demonstrating a C# interface that can be called using this method: github.com/dotnet/docs/issues/18174#issuecomment-642124735 People should refer to the DNNE documentation for how to create a DLL. This is a very new feature (.NET 5.0 is still in beta) but as it was not mentioned anywhere on SO I assumed it would be ok to not have more inline content yet. Moreover the other answer was found helpful (+5) despite not having inlined code.
What is "DNNE" for? ".NET native exports"?
@PeterMortensen I would guess like you: "Dot Net Native Export"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.