0
votes

I'm making a client/server program (it's a model of a system I'm working with) with .NET sockets for ease of use. Everything is going swimmingly and the data all gets sent; the biggest issue has been with the char array.

The packet I'm sending is essentially a bunch of doubles and a char array inside a struct (this is necessary/essential as it models the packet on the system I am mimicking). All the doubles are working just fine however the char array is a bit trickier because the array needs to be 4 bytes/characters long.

I've been using the marshalling library to handle the byte data as well as the Char array buffer size of 4 like so:

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public char[] tmp;

I also use: [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] to make sure my chars are 1 byte. The server that will eventually read my client program is in C and I want to make sure the types line up just so.

Anyway, my current server program I'm using to test the stuff receives the packet and everything A ok, however when i try to print it for debugging purposes the char array doesn't exactly go according to plan.

I have a large string that I put all the stuff into like so:

return_str += "\nChar Array (tmp) : " + str.tmp;

And then I print it with a later function call.

What is printed is the following:

 System.Char[] .

Instead of what I specified the char array to be (IE, ABCD or something similar).

The way I specify my packet values is with a windows form app with sliders and text boxes etc. Like I said, the doubles all communicate their values perfectly but this is another issue.

I'm not sure if this an issue with the marshalling code or simply something I'm missing with char arrays.

Could really use some help

1

1 Answers

3
votes

Calling ToString() on a char[] will print exactly what you're seeing.

You need to turn your char[] into a string using new string(str.tmp).

If you're reading strings, consider using a byte[] instead, and then using System.Encoding.Text to read the string (there are encoders for ASCII and various UTF variants).