Sunday, March 20, 2011

Converting a .NET object to (byte*)

Is there a way to cast a System.Object to byte*?

From stackoverflow
  • According to Jon Skeet, it is possible through just casting it to a byte array.

    Michal Franc : I need cast to unsafe pointer. I ve made a workaround. Passing int through function. I can easily convert byte* to int and int to byte*. But still the question is here.
    streetparade : @steven i postet jon skets code above ;-)
    monksy : After I posted the source.
  • Just use:

    byte[] b = (byte[]) myobj;
    
  • How about something like...

    BinaryFormatter bf = new BinaryFormatter();
    System.IO.MemoryStream ms = new System.IO.MemoryStream(1024);
    
    Object1 blah = new Object1("Hello");
    
    bf.Serialize(ms, blah);
    byte[] bytes = ms.GetBuffer();
    
  • OK, I found the solution:

    (byte*)(int)someObject
    
    Jan : What if someObject is larger than an int?
    Michal Franc : In my scenario it wont happen. But yes you are right.
    Hans Passant : Doesn't work in 64-bit mode. A pointer is larger than an int.

0 comments:

Post a Comment