简体   繁体   中英

Wrapping C# C++

I would like to wrap a native library with C++/CLI. It's work with primitive type. But in the following case, it's more complicated :

interface ISampleInterface
{
    void SampleMethod();
}

public ref class NativeClassWrapper {
    NativeClass* m_nativeClass;

public:
    NativeClassWrapper() { m_nativeClass = new NativeClass(); }
    ~NativeClassWrapper() { delete m_nativeClass; }
    void Method(ISampleInterface ^i) {
        ???
        m_nativeClass->Method(i);
    }
};

How to wrap this ? Because the native code C++ doesn't know the ISampleInterface type... (Same question with a virtual class)

Thanks you.

If your native class needs to callback into .NET code, you need to use the gcroot template. Wuth this you can store the managed object in an unmanaged class. In this unmanaged class you can then use a native "callback" and then use the member stored in `gcroot´ to callback into managed code (ISampleInterface).

See also:

There are some mistakes in the code snippet. Let's start with a clean example, declaring the native class first:

#pragma unmanaged
class INativeInterface {
public:
    virtual void SampleMethod() = 0;
};

class NativeClass {
public:
    void Method(INativeInterface* arg);
};

And the managed interface:

#pragma managed
public interface class IManagedInterface
{
    void SampleMethod();
};

So what you need is a native wrapper class that derives from INativeInterface so that you can pass an instance of it to NativeClass::Method(). All that this wrapper has to do is simply delegate the call to the corresponding managed interface method. Usually a simple one-liner unless argument types need to be converted. Like this:

#pragma managed
#include <msclr\gcroot.h>

class NativeInterfaceWrapper : public INativeInterface {
    msclr::gcroot<IManagedInterface^> itf;
public:
    NativeInterfaceWrapper(IManagedInterface^ arg) : itf(arg) {};
    virtual void SampleMethod() {
        itf->SampleMethod();
    }
};

Now your method implementation becomes easy:

void Method(IManagedInterface^ i) {
    NativeInterfaceWrapper wrap(i);
    m_nativeClass->Method(&wrap);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM