Wrapping managed code for unmanaged use

2019-02-25 00:15发布

问题:

We have a big C++ project that's compiled as native unmanaged code. We need to use a feature from managed code, but we don't want to compile the whole project in /clr.

So I made a DLL, have a ref class named B, which is exposed in exported native class A. Problem is I get a C1190: managed targeted code requires a '/clr' option because of the vcclr.h include.

I'd like to know if there is a way to create some kind of interface that will have managed code within unmanaged methods.

Here's my code:

#pragma once
#include "EX_Port.h"
#include <vcclr.h>

ref class B;

class EX_API A
{
    public:
        A();        
        int DeviceCount();

    private:
        gcroot<B^> _device;
};

I managed to make it work by gcnew the B class within the cpp. But then I have a local object while I'd like to have it in the global scope. I just began doing CLI programming so I might not be aware of some practices.

Thanks

回答1:

Your big C++ program is going to have to load and initialize the CLR before it can execute any managed code. There are several ways to do this, ranked from most flexible to least:

  • It can use the CLR hosting interface to explicitly load the CLR and execute arbitrary managed code. Basic starter for that is this MSDN page and the many examples you can find on sites like CodeProject.com

  • You can make your managed classes [ComVisible]. Your C++ code then can use standard COM programming techniques to create an instance of the managed class and call its methods (CoInitializeEx and CoCreateInstance, the #import directive). The COM plumbing ensures that the CLR is automatically loaded and loads the proper assembly, no additional code is required to manage that yourself. Consider this option when you already have an investment in COM, not otherwise something you should consider if you have no working knowledge of COM.

  • The two above techniques allow any kind of managed code to be executed, not just C++/CLI code. Specific to C++/CLI, you can write a free function and apply the __declspec(dllexport) attribute to it. The compiler will generate a stub that exports the function so you can call it from your C++ code with LoadLibrary + GetProcAddress. The stub automatically loads the CLR. This is very easy to get going but is pretty inflexible since you are only exposing a simple function and not a class.