1

I would like to ask your guidance of how to call a C++ .dll from C# and process/share the result with C#.

Let's say I have a call e.g processFile which returns a struct called ResultDetails. How can I share/use this object in C# given that I use CMake and preferrably mingw-gcc.

(Probably I won't be able to share the object as it is, but is it possible to somehow serialize it to a C# compatible format and desirialize it in C#.(I would not prefer to serialize the result to JSON write it to a file and read it from C#.))

Sample c++ header

ResultDetails* processFile(char *filePath);

struct ResultDetails {
    std::vector<std:Exception> exceptions;
    Geometry geometry;
    std::vector<Surfaces> surfaces;
}

Any idea is appreciated, Thank you for your time and patient

flatronka
  • 1,061
  • 25
  • 51
  • You won't be able to return a C++ type like `vector` into a C# application. – Sean Nov 17 '17 at 10:32
  • @Sean Thank you for the quick response. There has to be some way of going around this. e.g. extending ResultDetails with functions like resultDetails.surfaces(i) or something similar. Would that work? – flatronka Nov 17 '17 at 10:36
  • You can't pass classes from c++ to c#, you only can get the pointer, not the class itself. Depending on the usage of the data you can convert all the data to structures, else you must create wrapper classes on C# and multiple exported functions on the library to manage the c++ classes. – Gusman Nov 17 '17 at 10:45
  • @Gusman thank you for your answers, could you provide examples of how to do your proposed solutions? how should I create a the wrapper classes? and how to convert pointer to structures? – flatronka Nov 17 '17 at 11:33

1 Answers1

0

Actually, it looks like a .NET matter. If you turn your library into a CLR project (i.e. compile it as a mixed assembly), you can easily (more or less) wrap your struct inside a .NET one, which in turn will be available to whatever C# client that would use it.

I think you can start from here: https://learn.microsoft.com/en-us/cpp/dotnet/mixed-native-and-managed-assemblies

p-a-o-l-o
  • 9,807
  • 2
  • 22
  • 35
  • Dear @p-a-o-l-o, Thank you for your answer. Unfortunately, I can't do that, since I am using CMake and GCC. GCC is not hard requirement I can use VisualC++, but CMAKE is a hard requirement which limits me of using CLR. – flatronka Nov 17 '17 at 11:38
  • @flatronka CMake has [no problem with compiling C++/CLI code](https://stackoverflow.com/questions/12503229/c-cli-and-cmake), as long as you use a compiler that supports this. – ComicSansMS Nov 19 '17 at 08:07