0

Hello I am trying to pass a pointer address from a managed class to an unmanaged class. So every A-Object has a reference to a B-object. But if I pass the reference in _a = new A(_managedB->_b) the compiler throws an error that no constructor matches the argument list.

So what's wrong with the code?

unmanaged code:

class A
{
private:
    B &b;
public:
    explicit
        A(B& b);
        ~A();
}

managed code:

public ref class ManagedA
{
private:
    ManagedB ^_managedB;
    A *_a;
public:
    ManagedA::ManagedA(ManagedB ^managedB ): _managedB(managedB)
    {
        _a = new A(_managedB->_b);
    }
    ManagedA::~ManagedA(ManagedB ^managedB ): _managedB(managedB)
    {
        delete _a;
        _a = 0;
    }
};
fejese
  • 4,601
  • 4
  • 29
  • 36
Franki1986
  • 1,320
  • 1
  • 15
  • 40
  • A managed pointer and an unmanaged reference are not the same thing. You need to pin the object. – Sebastian Redl Jun 30 '15 at 10:07
  • You can't take a (native) reference to (or address of) a managed object -- you either have to pin it in memory (otherwise the GC has the right to move it around willy nilly) or use managed references (`ManagedB^`). – Cameron Jun 30 '15 at 10:09
  • So I tried folowing: pin_ptr pointerB = _managedB->_b; _a = new A(pointerB); Whats is wrong with this? Sorry for the questions, but I am new in managed C++. Has anybody an example for this? – Franki1986 Jun 30 '15 at 10:34

1 Answers1

1

Ok I did it like this and it worked. I don't know if the situation is interpreted right, but I am not trying to pass a Handle as a pointer. I pass a pointer that is a member of an Handle.

public ref class ManagedA
{
private:
    ManagedB ^_managedB;
    A *_a;
public:
    ManagedA::ManagedA(ManagedB ^managedB ): _managedB(managedB)
    {
        _a = new A(*_managedB->_b);
    }
    ManagedA::~ManagedA(ManagedB ^managedB ): _managedB(managedB)
    {
        delete _a;
        _a = 0;
    }
};
Franki1986
  • 1,320
  • 1
  • 15
  • 40