Casting managed array

  • Thread starter Stewart Stevens
  • Start date
S

Stewart Stevens

I have a structure that looks like this:

[StructLayout(LayoutKind::Sequential)]
public __value struct mytype
{
float first;
float second;
};

I am trying to pass arrays of these things over a socket. So I have:

mytype items __gc []

and need to provide

Bytes rawbytes __gc []

to the socket code.

Right now I am using BitConvertor to do this conversion. It works for the
moment but I don't consider this acceptable. Partly because of the obvious
inefficiency but mostly because I want to use the same socket code to deal
with simple arrays of managed floats. I've tried many ways of casting the
array and it's just not happening.

Type saftey isn't a big concern for me at this level because the code is
private to my assembly. (The same assembly contains implementations for
both sides of the socket.) I wanted to use dotnet rather than win32
sockets because my client is written entirely in managed code.

Can anyone help me with a trick for those arrays?
 
M

Mattias Sjögren

Stewart,

For an array of float you should be able to use Buffer::BlockCopy to
copy the bits to a byte array.

For an array of your mytype struct, you would have to pin the array
and memcpy the content to a byte array (that's also pinned).

There's no way to cast between the different array types, so you'll
always have to duplicate the data.



Mattias
 
N

Niki Estner

You should look at the Marshal class; It contains copying functions that
that can do these kinds of conversions. Also, binary serialization might be
interesting to you.

Niki
 
S

Stewart Stevens

Thanks very much....that makes things a lot tidier.
I was a bit hung up on avoiding the copy....
 
S

Stewart Stevens

I am new to dotnet ... but I got the impression that the Marshal class was
used for moving data between managed and unmanaged code ... this situation
is all managed so the Buffer class that Mattias mentioned seems more
appropriate.

The binary serialization is actually exactly what I want to avoid. Most of
my interface exploits the safety and conveniance of the Remoting
architecutre using binary serialization but I have to move a lot of data
quickly and the binary serialization is totally inappropriate for that. Not
only is the serialization time consuming but there is a serious size
overhead....400 bytes worth of my simple float structures are serialized to
1051 bytes!

My first stab at the socket implementation - with the inefficiencies I was
complaining about in my post (+ some other problems I am fixing!) gave me
up to 10 fold speed increase.

Cheers
Stewart
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top