Marshalling strings as fixed length WITHOUT null terminator.
From: Tajmiester (tristan_me_at_homail.com)
Date: 02/21/05
- Next message: (no email): "Cannot create WebApp ??"
- Previous message: juli jul: "Re: select a folder"
- Next in thread: Mattias Sjögren: "Re: Marshalling strings as fixed length WITHOUT null terminator."
- Reply: Mattias Sjögren: "Re: Marshalling strings as fixed length WITHOUT null terminator."
- Messages sorted by: [ date ] [ thread ]
Date: Mon, 21 Feb 2005 16:26:28 GMT
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
- Next message: (no email): "Cannot create WebApp ??"
- Previous message: juli jul: "Re: select a folder"
- Next in thread: Mattias Sjögren: "Re: Marshalling strings as fixed length WITHOUT null terminator."
- Reply: Mattias Sjögren: "Re: Marshalling strings as fixed length WITHOUT null terminator."
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|