4
votes

I have a method in my native dll, that I want to use. The method returns an object of a type that is also in my native dll.I am trying to write a c++/CLI wrapper.

Now,

  • Can I get a return value as the object using C++/CLI and how do I do that?
  • Can we store and pass the native C++ object?
  • Should I need to create my own class resembling the native C++ class?
  • How would I marshal a class?

For Example,My native dll has these classes,

class X
{
    /* some props and methods. */
};


Class Y
{
    X* someMethod();
};

I need to wrap the someMethod class using C++/CLI. Will I be able to get the return value in the CLI?

1
Search around SO a bit, I believe something like this has been done before... you can wrap your native code into a managed value class I think. - Kerrek SB

1 Answers

1
votes

Returning pointers to C++ objects from an exported function in a DLL is a pretty bad idea. It is a nasty memory management problem, you'd expect the client code to release the object. That can only come to a good end when both DLLs use the exact same version of the DLL version of the CRT (/MD compile option). If you can't recompile the native DLL then stop right now, you cannot make it work reliably or you'll have a big maintenance problem in the future.

Anyhoo, you need a wrapper for both classes. They should resemble this:

#pragma managed(push, off)
#include "xandy.h"
#pragma managed(pop)

using namespace System;

namespace something {

    public ref class XWrapper {
        X* mX;
    public:
        XWrapper(X* obj) : mX(obj) {}
        ~XWrapper() { this->!XWrapper(); }
        !XWrapper() {
            // Trouble is here!!!
            delete mX;
        }
    };

    public ref class YWrapper {
        Y* mY;
    public:
        YWrapper() { mY = new Y; }
        ~YWrapper() { this->!YWrapper(); }
        !YWrapper() { delete mY; }
        XWrapper^ someMethod() {
            return gcnew XWrapper(mY->someMethod());
        }
    };
}