Reputation: 117
I'm trying to do a little "memcpy" hack in C#. I keep getting stuck on this part, because it won't convert System.Type to byte*
public unsafe void memcpy(byte* dest, object src, int length)
{
byte* nsrc;
byte* ndst;
nsrc = (byte*)((src.GetType())src);
}
As you see I try to get the type of the object, and then cast it to the original object.
Any ideas?
Update:
Maybe using serialization?
private byte[] ObjectToByteArray(Object obj)
{
if(obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
private void memcpy(byte[] dest, int pos, object src, int len)
{
byte[] ba = ObjectToByteArray(src);
Array.Copy(ObjectToByteArray(src), 0, dest, pos, len);
}
Upvotes: 0
Views: 265
Reputation: 61952
Not clear what you want, but maybe this is helpful?
int yourInt32 = ...;
byte[] bitsFromInt32Value = BitConverter.GetBytes(yourInt32);
long yourInt64 = ...;
byte[] bitsFromInt64Value = BitConverter.GetBytes(yourInt64);
Upvotes: 3
Reputation: 4542
taken from msdn:
Pointer types do not inherit from object and no conversions exist between pointer types and object. Also, boxing and unboxing do not support pointers. However, you can convert between different pointer types and between pointer types and integral types.
link:http://msdn.microsoft.com/en-us/library/y31yhkeb(v=vs.100).aspx
int number = 200;
unsafe
{
// Convert to byte:
byte* p = (byte*)&number;
}
Upvotes: 0