How to use managed code from unmanaged code?

蹲街弑〆低调 提交于 2019-12-09 00:04:43

问题


How do I call a .NET code from native C++ (unmanaged code)? I want to expose .NET code to my unmanaged (C++) application and then use them. More specifically, I want to call C# from native C++ :). I know there are many ways but can you tell me the pros and cons of each? By the way, I don't want to use COM so what are the options now?

Is it possible that I wrap the C# code in C++/CLI and then call it from C++? If so, how do I do that? How do I wrap the C# in C++/CLI and then call it from C++?


回答1:


I've written about it just recently. It was about Delphi, but that doesn't mean it won't work with C++ as well.

.NET component in DELPHI 2009

Even without knowing much about C++, I still know that IUnknown and COM-compatible interface references should be usable just fine from C++ (in the case you need to pass objects, not just structures).

  • You can use Microsoft's C++/CLI to reference your C# code and export it as ordinary DLL functions.
  • You can also download an MSBuild task I wrote, that allows you to export function directly from C#. Analogous to how DllImportAttribute is used.

This C# code would export a function "YourExportName" that can be used just like any c-compatible function would be used.


class Sample
{
   [DllExport("YourExportName")]
   static int TestFunction(int left, int right)
   {
     return left + right;
   }
}



回答2:


You can always embed Mono. I have personally done it in two projects so far and it's easy enough. Follow Embedding Mono for more information.




回答3:


You could expose the managed component as COM object.




回答4:


Check How to call a managed DLL from native Visual C++ code in Visual Studio.NET or in Visual Studio 2005



来源:https://stackoverflow.com/questions/1635679/how-to-use-managed-code-from-unmanaged-code

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