By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,180 Members | 1,106 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,180 IT Pros & Developers. It's quick & easy.

Marshalling strings as fixed length WITHOUT null terminator.

P: n/a
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/article...es-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
Nov 16 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
>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

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 16 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.