Memory Copy in C#

  • Thread starter Thread starter Tash Robinson
  • Start date Start date
T

Tash Robinson

I am new to C# and have searched for an answer to this problem, but
haven't found anything that I understand. Maybe someone can point me
in the right direction.

I have a VB6 project I am trying to rewrite in C#. It talks to a
specific device using a COM server component. There is a method to
return the status of the device, in C# the return type is object.
This object is actually 284 bytes. In VB I could just use CopyMemory
to copy this object to an instance of a userdefined type that I could
then use access the individual members.

I understand that in C# CopyMemory is not really the right way to do
things, and the data sizes are different anyway (32 bit for integer
instead of 16, etc..)

What is the best way to access the object and assign, for example, the
first 2 bytes to a C# integer, the next 40 bytes to an array of 10
longs, etc...
If possible without using unsafe code...

Can someone point me in the right direction. I can search and
research if I have some idea where to look.

Thanks!!
 
Tash Robinson said:
I am new to C# and have searched for an answer to this problem, but
haven't found anything that I understand. Maybe someone can point me
in the right direction.

I have a VB6 project I am trying to rewrite in C#. It talks to a
specific device using a COM server component. There is a method to
return the status of the device, in C# the return type is object.
This object is actually 284 bytes. In VB I could just use CopyMemory
to copy this object to an instance of a userdefined type that I could
then use access the individual members.

I understand that in C# CopyMemory is not really the right way to do
things, and the data sizes are different anyway (32 bit for integer
instead of 16, etc..)

What is the best way to access the object and assign, for example, the
first 2 bytes to a C# integer, the next 40 bytes to an array of 10
longs, etc...
If possible without using unsafe code...

What is the data type the COM server uses for the return value (in IDL or in
VB)?

It's not object, I bet. It's either variant or some sort of byte array.

You probably need to figure out what the interop data type is for such a
byte array, I assume it's probably byte[] in C#. You can try typecasting
your return value (call it ret, for instance) that is of type object to a
byte[] and see what happens.

For instance, if ret is your variable (of type object) for the return value,
do something like:
byte[] newret = ret as byte[];
if(newret == null) {
/// this is an invalid typecast, so try something else, print
ret.GetType().FullName, for instance
} else {
/// this is the type you should use and just read the items from the
byte[] array as necessary, maybe using one of the System.IO.xxxReader types.
}

Kelly
 
Thanks Kelly that works great!

I was trying to cast it to a byte array but could not get the syntax.


Thanks again!
 
Back
Top