Question

I've got a legacy managed c++ dll, and I need to call some function which is returning a managed type.

For dllexports without managed types, this is easy, I just define my static c(++) function in a header like this:

extern "C" 
{
  __declspec(dllexport)  int  __cdecl  InitSystem();
}

But now the static c(++) function should return a managed type, and here I got a problem. If I try (for example):

extern "C" 
{
  __declspec(dllexport)  System::Collections::Generic::List<System::String^>^  __cdecl  InitSystem();
}

I get a compiler error (function definition needs __clrcall signature).

Since the DLL is not an assembly (I think), I'm a bit at a loss how to export a simple function call using .net/clr parameters. This probably is simple and I'm just looking in the wrong direction?

Was it helpful?

Solution

It has to be an assembly, there's no other way to build code with a managed type like that. Mixing managed and native code in one assembly is fine. Which automatically solves the problem, the function will be available in the metadata, no need to export it. You need to drop all the decoration, it cannot be applied to a managed method. And it should be in a ref class to allow other managed languages to use it.

public ref class Mumble {
public:
    static System::Collections::Generic::List<System::String^>^  InitSystem();
};

A C# program now can use var lst = Mumble.InitSystem(). Using a namespace is recommended.

Watch out for /clr btw, it will readily convert native code to IL without complaint. Either turn off /clr on a source code file or use #pragma managed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top