How to use managed code from unmanaged code?

前端 未结 4 2073
遥遥无期
遥遥无期 2021-01-03 01:38

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

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-03 02:13

    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;
       }
    }
    

提交回复
热议问题