By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,892 Members | 1,251 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,892 IT Pros & Developers. It's quick & easy.

Get IntPtr to Current Object?

P: n/a
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);
}
Jul 11 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On Jul 11, 9:17 am, "O.B." <funkj...@bellsouth.netwrote:
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);
}
}
}
Jul 11 '08 #2

P: n/a
On Jul 11, 6:17*pm, "O.B." <funkj...@bellsouth.netwrote:
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.
Jul 11 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.