Skip to content

Instantly share code, notes, and snippets.

@itsff
Last active December 24, 2015 15:09
Show Gist options
  • Save itsff/6818217 to your computer and use it in GitHub Desktop.
Save itsff/6818217 to your computer and use it in GitHub Desktop.
C++/CLI implementation of SafeBuffer class that wraps std::unique_ptr<const char*>. This allows for creation of UnmanagedMemoryStream and saves copying of data between the native and managed sides. I still need to figure out how to handle custom deleters.
ref class CppSafeBuffer : public ::System::Runtime::InteropServices::SafeBuffer
{
private:
// TODO: Figure out how to handle a custom deleter
//std::unique_ptr<const char*>::deleter_type _deleter;
public:
CppSafeBuffer(std::unique_ptr<const char*> && bytes,
const std::size_t size)
: ::System::Runtime::InteropServices::SafeBuffer(true)
{
//_deleter = bytes.get_deleter();
SetHandle( IntPtr(bytes.release()) );
Initialize(size);
}
protected:
virtual bool ReleaseHandle() override
{
const char* ptr = (const char*) handle.ToPointer();
//TODO: Figure out how to handle deleters: _deleter(ptr);
delete ptr;
SetHandleAsInvalid();
return true;
}
};
void sampleUsage( std::unique_ptr<const char*> && msg, const std::size_t msgSize )
{
using namespace ::System;
using namespace ::System::IO;
auto memStream = gcnew UnmanagedMemoryStream(
gcnew CppSafeBuffer(std::move(msg), msgSize),
0,
msgSize,
FileAccess::Read);
::System::Console::WriteLine(memStream->Position);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment