Get IntPtr to Current Object?

O

O.B.

I have a class that has an Explicit StructLayout. In the constructor
below, I am copying data from a byte array onto this class so as to
initialize all the explicit attributes of the class. What I don't
like is the overhead of allocating memory for a temporary variable
(pData) when I want to marshal the data in the rawData array directly
into the current object. Would there be a way to get an IntPtr
directly to the current object?

public EntityState(byte[] rawData)
{
IntPtr pData = Marshal.AllocHGlobal(rawData.Length);
Marshal.Copy(rawData, 0, pData, 144);
Marshal.PtrToStructure(pData, this);
Marshal.FreeHGlobal(pData);
}
 
O

O.B.

I have a class that has an Explicit StructLayout. In the constructor
below, I am copying data from a byte array onto this class so as to
initialize all the explicit attributes of the class. What I don't
like is the overhead of allocating memory for a temporary variable
(pData) when I want to marshal the data in the rawData array directly
into the current object. Would there be a way to get an IntPtr
directly to the current object?

public EntityState(byte[] rawData)
{
IntPtr pData = Marshal.AllocHGlobal(rawData.Length);
Marshal.Copy(rawData, 0, pData, 144);
Marshal.PtrToStructure(pData, this);
Marshal.FreeHGlobal(pData);

}

Actually, I think this will work. Any gotchas that I should be aware
of?

public EntityState(byte[] rawData)
{
unsafe
{
fixed (byte* pData = rawData)
{
Marshal.PtrToStructure((IntPtr)pData, this);
}
}
}
 
P

Pavel Minaev

I have a class that has an Explicit StructLayout.  In the constructor
below, I am copying data from a byte array onto this class so as to
initialize all the explicit attributes of the class.  What I don't
like is the overhead of allocating memory for a temporary variable
(pData) when I want to marshal the data in the rawData array directly
into the current object.  Would there be a way to get an IntPtr
directly to the current object?

You can't get a pointer to an object, but you can just get a plain
pointer to the first data member (using operator unary & as usual),
which, if you did the layout correctly, should be equivalent. Just
don't forget to pin it using "fixed". A pointer can then be cast to
IntPtr.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top