export function with clr parameters from dll?

与世无争的帅哥 提交于 2019-12-20 03:37:26

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/4546425/export-function-with-clr-parameters-from-dll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!