How to return managed this pointer

38 views Asked by At

This is probably a simple noob user-error, And I feel dumb not figuring this out myself. I have some old unmanaged code that I need to convert to managed c++ .net, because I want to Serialize the objects. My question is not about serialization however, but about why my new code won't compile. How can I retrieve the 'this' pointer in the class by returning it from a managed function. I don't know why return the 'this'-pointer from this new class is not working.

I changed

struct PixelBuffer

to

public ref class PixelBuffer or ref struct PixelBuffer

I changed

PixelBuffer *PixelBuffer::GetData()
{
    return this;
}

to

PixelBuffer ^PixelBuffer::GetData()
{
    return this;
}

The compiler does not like the last change. And it shows a red line under the ^-symbol.

The error shown: Handle to a non-managed class is not allowed

I wasn't able to find anything on the web. I searched and searched for managed pointers but C++ .net is not giving any results. Tried the same thing with C# .net with no results either.

1

There are 1 answers

0
Natural Number Guy On

The solution was not to define the GetData() function in the cpp file defintions, but in the header file.

in pixelbuffer.h:

PixelBuffer^ GetData()
{
    return this;
}

instead of:

PixelBuffer^ GetData();