Jump to content
  • Advertisement
Sign in to follow this  
Zbychs

[.net] How to return pin_ptr?

This topic is 3618 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I know that returning pin_ptr<> from a function is illegal. But what I have is this:
//unmanaged
struct Buffer : IBuffer {
    gcroot<array<UInt32>^> buffer;
    void* lock() {
        pin_ptr<UInt32> buf = &buffer[0]; //interior_ptr would be even better
        return (void*)buf; //illegal! pin_ptr gets destroyed!
    }
    void unlock() {
        //release the pin somehow
    }
}

//unmanaged
void func(Buffer& buffer) {
    uint32* buf = (uint32*)buffer.lock();
    //do stuff
    buf[0] = 5;
    buffer.unlock();
}

I need to return void* from lock(), cause IBuffer is an unmanaged class with virtual void* lock() method. I also want to keep Buffer::buffer as a managed array, cause I'm gonna use it in managed functions (and don't want to copy a native buffer to a new managed array every time). So, is there a way to pin a managed array and return a valid unmanaged pointer to it? Zbyl

Share this post


Link to post
Share on other sites
Advertisement
Try using a GCHandle:


using namespace System::Runtime::InteropServices;

struct Buffer : IBuffer {

gcroot<array<UInt32>^> buffer;
GCHandle handle;

void* lock() {
handle = GCHandle::Alloc(buffer, GCHandleType::Pinned);
// get pointer to array data
return handle.AddrOfPinnedObject().ToPointer();
// You could use the following alternatively which reveals better
// what you are doing, but it is probably slightly slower.
//return Marshal::UnsafeAddrOfPinnedArrayElement(buffer, 0).ToPointer();
}

void unlock() {
handle.Free();
}
};




Regards,
Andre

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!