Marshalling a string to a byte array and back RRS feed

  • Question

  • hey guys, im wondering how the best way to approach the following problem. I am converting a C++ application into a web service that talks to another host server via tcp.
    the older app had a struct of multiple c-style strings, all set to null such as:
    struct myStruct
    char buf1[10];
    char buf2[100];
    char bufN[10];

    we'd memset it to 0x00 and fill in some of the needed buffers.
    we would then tcp it to a host by casting the struct to a char*
    tcp_send( n_handle, (char*)stc_mine, sizeof(stc_mine) );

    the host knows the same struct layout, basically copying the recieved buffer to their struct layout. they get the needed info, fill in the missing data in the structure and send back a response.

    i want to convert this to a C# app and my idea was this, make a struct filled with strings, default all the strings to the same size as the C version, padded with 0x00. ive created a working communication representing the string buffers as byte arrays
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1, Size=1000)]
    public struct Stc_Mine
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
    byte[] buf1; // size 10
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)]
    string buf2; // size 100
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
    string bufN; // size 10
    i fill in the buffers, convert the structure to a byte array and send it to the host via TCP. i successfully receive a response and convert the byte array back to the structure with no problems.
    where i do have an issue is, id like to return the filled object from the web service. doing so creates a nice little xml tagged response but the data is still unreadable. 
    i tried using strings and marshalling them as UnmanagedType.ByValTStr but i have size issues since its adding a null terminator that i dont need.
    right now i have a parallel structure of all strings that i am converting the first structs members to and returning that object but it seems like a lot of extra work when theres already an inherit way to do this, but its just not producing the desired effect.
    i tried to marshal a string as a UnmanagedType.ByValArray but recieved exceptions about bad marshalling types. is there another way to accomplish this?
    • Moved by jack 321 Monday, July 7, 2008 7:05 AM off topic
    Wednesday, July 2, 2008 9:15 PM

All replies