Marshalling strings as fixed length WITHOUT null terminator.


T

Tajmiester

Hi, And thanks for any help.

I am having trouble declaring a struct containing strings that can be
Serialized using the following functions. It works, but the strings wont
store the right number of characters, they store one less with a null at the
end! Whats the point in a marshalling as fixed length if it wastes space
with a null! How can i make it marshall the strings as "proper" fixed length
strings, where the full 8 (or 3) characters can be stored without having to
extend the length of the strings.
/* Generic serialization functions */

/* Thanks to Peter Petrov @
http://csharp.codenewbie.com/articles/csharp/1431/C_and_advanced_binary_files-Page_1.html
*/

public class RawSerializer

{


public static byte[] RawSerialize( object anything )

{

int rawsize = Marshal.SizeOf( anything );

IntPtr buffer = Marshal.AllocHGlobal( rawsize );

Marshal.StructureToPtr( anything, buffer, false );

byte[] rawdatas = new byte[ rawsize ];

Marshal.Copy( buffer, rawdatas, 0, rawsize );

Marshal.FreeHGlobal( buffer );

return rawdatas;

}


public static object RawDeserialize( byte[] rawdatas, Type anytype )

{

int rawsize = Marshal.SizeOf( anytype );

if( rawsize > rawdatas.Length )

return null;

IntPtr buffer = Marshal.AllocHGlobal( rawsize );

Marshal.Copy( rawdatas, 0, buffer, rawsize );

object retobj = Marshal.PtrToStructure( buffer, anytype );

Marshal.FreeHGlobal( buffer );

return retobj;

}

}



[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]

public struct FileInfoRecord

{

public uint fileId;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]

public string fileName;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 7)]

public string fileType;

public uint fileDirectory;

public DateTime fileModified;

public DateTime fileCreated;

public uint fileSize;

}

Thanks

Tristan
 
Ad

Advertisements

M

Mattias Sjögren

How can i make it marshall the strings as "proper" fixed length
strings, where the full 8 (or 3) characters can be stored without having to
extend the length of the strings.

Replace the strings with char[] and change the marshaling setting to
ByValArray.



Mattias
 

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