Runtime: Recommended way of exposing C++ data and interfaces to .NET core

Created on 5 Oct 2017  路  6Comments  路  Source: dotnet/runtime

Since there is no C++/CLI, what is the recommended way of exposing C++ data and interfaces to .NET core? Is it C style functions and P/Invoke (for cross platform apps, how would you reference different dynamic library names)? Some kind of (inter-process) communication?

area-Interop-coreclr question

Most helpful comment

cc @russellhadley

https://github.com/mono/CppSharp is one built by the Xamarin folks which we recommend.

It would be nice to have an example that shows how to use this tool with .NET Core.

All 6 comments

PInvoke and COM interop are the recommended ways.
Did you consider unifying the dynamic library names across all platforms you need to support? An alternative would be to cross-compile for specific distros ...

cc @janvorli

Is there an example on how to create C++ COM interface for non-Windows OS?
What I meant for different library names is .dll on Windows, .so on Linux, etc...

Is it C style functions and P/Invoke

Yes, this is the way you should do it. This will be the easiest and most portable option.

(for cross platform apps, how would you reference different dynamic library names)?

If you control it, you should ensure that the library names (barring file extension) are identical. If they are not identical, then the problem becomes significantly harder (see https://github.com/dotnet/coreclr/issues/930).

CoreCLR will automatically prepend "lib" to the dll name when resolving PInvokes, and will also append ".so" or ".dylib" depending on what is appropriate for the platform. This means you can write this:

[DllImport("mylib") void DoThing()

And CoreCLR will load that function from these names:

  • mylib.dll
  • mylib.so
  • mylib.dylib
  • libmylib.so
  • libmylib.dylib

You need to ensure that "mylib" is the common name on all platforms, though. You also need to ensure there are no extra periods in the string (including in a ".so.1"-style suffix), or CoreCLR will not find the binary.

If you have to do a lot of C# / C++ interop we recommend that you autogenerate the interop code. There are number of tools that do that, e.g. https://github.com/mono/CppSharp is one built by the Xamarin folks which we recommend.

cc @russellhadley

https://github.com/mono/CppSharp is one built by the Xamarin folks which we recommend.

It would be nice to have an example that shows how to use this tool with .NET Core.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

yahorsi picture yahorsi  路  3Comments

GitAntoinee picture GitAntoinee  路  3Comments

jzabroski picture jzabroski  路  3Comments

matty-hall picture matty-hall  路  3Comments

EgorBo picture EgorBo  路  3Comments