2

I know that C# allows interoperability with native code using PInvoke (An Overview of Managed/Unmanaged Code Interoperability)

We are planning to develop new code, and are considering 2 options:

  1. Native solution + managed (C#) wrapper around interop code that calls the native code.
  2. Fully managed solution

I would like to know whether there are any documented limitations to this interop ? (e.g - certain types that cannot be marshalled back and forth between managed/native, etc)

These limitations can affect our decision to use (or not use) option #1.

lysergic-acid
  • 19,570
  • 21
  • 109
  • 218

1 Answers1

5

P.O.D. (plain-old-data) structs are generally fairly easy to marshal.

But if you want to marshal complex C++ classes that contain things like vectors, then you'll run into trouble.

If you can write C/C++ code to transform complex classes into simpler types for calling via p/invoke then that's ok - but otherwise, run away from complex C++ classes.

However, there is another possibility.

You can use the so-called "It just works" technology to wrap C++ code using a CLI C++ class. You can mix unmanaged and CLI code in C++ - even in the same file - which can really help.

See here for more details:

http://msdn.microsoft.com/en-us/library/ms173185.aspx

http://www.windowsdevcenter.com/pub/a/dotnet/2003/03/03/mcppp2.html (this is rather old)

http://www.codeproject.com/Articles/651516/Exposing-native-to-managed-Cplusplus-CLI-vs-P-Invo

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • It may be also possible that the low-level C++ code will be out of my hands (e.g: using an existing library). This can make it harder to force these native structs to be "marshal friendly" – lysergic-acid Jan 27 '14 at 13:20
  • 2
    @lysergic-acid You may be able to wrap the lower level structs in managed C++ classes, and use those from C#. – Matthew Watson Jan 27 '14 at 13:22
  • @lysergic-acid You can always wrap any library and call it from p/invoke or mixed mode C++/CLI – David Heffernan Jan 27 '14 at 13:34
  • 2
    @MatthewWatson It is not called managed C++. Its official name is C++/CLI. – David Heffernan Jan 27 '14 at 13:34
  • @DavidHeffernan True - Managed C++ was deprecated ages ago. – Matthew Watson Jan 27 '14 at 13:39
  • What has C++ got to do with the original OP question of using C#? Just curious – Fandango68 Jan 15 '18 at 02:16
  • ps. I have the same problem as what OP said, but only using C#. The problem for me is how to give access to the interop DLL across multiple users logged on at the same time. Currently the application drops out with "object undefined" errors because one person has locked the DLL, whilst the other has not. The later person is getting the error. – Fandango68 Jan 15 '18 at 02:18
  • @Fandango68 Because C++/CLI can call unmanaged C++ code directly, and C# can call C++/CLI code directly, which gives you a route to (indirectly) call unmanaged C++ code from C# code. – Matthew Watson Jan 15 '18 at 08:40