1
votes

We are in the process of converting C# code to C++, but we need to do so in phases. I am at a point now where I need to instantiate several native objects from within managed code. These native objects I cannot change, and their declaration looks like this:

public class NativeA();
public class NativeB(std::shared_ptr<NativeA> obj);

Both NativeA and NativeB need to be instantiated from managed code as:

void main() {

    ManagedA ObjectA = gcnew ManagedA();
    ManagedB ObjectB = gcnew ManagedB(ObjectA);

}

The problem comes in with getting the shared_ptr of NativeA in the constructor of NativeB. Niether NativeA nor NativeB will be manipulated in managed code, they just need to be instantiated. Ideally, something like this:

public ref class ManagedA {
public:
    ManagedA() { _object = new NativeA(); }
    ~ManagedA() { delete _object; }

    NativeA * Get() { return _object; }

private:
    NativeA *_object;
};

public ref class ManagedB {
public:
    ManagedB(ManagedA^ objectA ) { 
        _object = new NativeB(std::make_shared<NativeA>(*objectA->Get()); 
    }
    ~ManagedB() { delete _object; }

private:
    NativeB *_object;
};

But, this is not allowed in c++/cli because native types are declared as private. Defining #pragma make_public(NativeA) does not solve this either.

My intent is not to work with the native objects in managed code, they just need to be instantiated, so I really don't care about trying to marshal the native pointers and deal with .NET GC if I don't have to, and I don't want to perform a copy. I just want to wrap the classes in order to pass them around.

Is there a clean and simple way to do this?

1

1 Answers

-1
votes

It appears that the answer was not due to a syntax or usage problem. The two managed objects were in different DLLs and could not be passed across them via .NET. Once the code was compiled in the same project, the issue was resolved.

Although the error message indicated the problem was an accessibility issue in VS 2015, and because it reported it during the link phase, I suspect the cause was because the linker would not have known about the implementation of the NativeA in NativeB without declaring an extern. Being wrapped in CLR, it surfaced as a different issue.