tags:

views:

92

answers:

4

I'm using a COM object that has a function called GetImage.

http://www.pdf-tools.com/asp/products.asp?name=P2IA

When I use it in Visual Studio 2008 it returns byte[], but when I use it in RAD Studio 2007 it returns System.Object. How can I get the data from the System.Object into a byte[]?

A: 

There is no data in an instance of Object itself. However since objects inherit from Object they may be referenced by an Object reference. To get data from the instance (assuming there is any) you have to cast the reference to the appropriate type.

Brian Rasmussen
A: 

Could you try with this function and see if it works:

public byte[] ToByteArray(object obj)
{
    int length = Marshal.SizeOf(obj);
    byte[] byteArray = new byte[length];
    IntPtr ptr = Marshal.AllocHGlobal(length);
    Marshal.StructureToPtr(obj, ptr, false);
    Marshal.Copy(ptr, byteArray, 0, length);
    Marshal.FreeHGlobal(ptr);
    return byteArray;
}
Darin Dimitrov
A: 

Thank you for answering. I tried the function, darin, rewritten as:

function ToByteArray(Obj : TObject) : TByteArray;
var
  Len : Integer;
  Ptr : IntPtr;
begin
  Len := Marshal.SizeOf(Obj);
  SetLength(Result, Len);
  Ptr := Marshal.AllocHGlobal(Len);
  Marshal.StructureToPtr(Obj, Ptr, false);
  Marshal.Copy(Ptr, Result, 0, Len);
  Marshal.FreeHGlobal(Ptr);
end;

but I got the error:

System.ArgumentException: Type 'System.Byte[]' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.

Any other ideas?

matthewk
A: 

It looks like Brian's answer was correct. It seems I can just cast the result of GetImage to TByteArray and it works.

Thanks both.

matthewk