How to: Add a fixed length string member in a struct

  • Thread starter Thread starter Zoury
  • Start date Start date
Z

Zoury

Hi folks! :O)

I found this posted by Matthias on february 2001 :
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)]
string blabla;

or this posted by Matthias on december 2003 :
[MarshalAs(UnmanagedType.ByValArray, SizeConst=123)]
public char[] chars;


in both scenario the OP needed to work with APIs. What I want to do is to
dump/read data from a customly formated file.

in VB 6, we could declare something like the following :
'***
Type MyType
Code As String * 3
Name As String * 25
End Type
'***
and then write/read the given Type directly into a file.


Would this be possible in C# using one of the above way (and a BinaryWriter
i guess) ?
 
Zoury,

The binary writer won't do much for you here, since it won't know how to
lay out the strings. You could write it directly to a file yourself through
the API, taking advantage of the marshaling infrastructure, but to be
honest, it is a bit overkill for something like this.

You are better of creating the structure, and having a specific class
what will format the output correctly to the file, and read the items from
the file (or rather, make it a stream, or a TextReader that you read from).

Hope this helps.
 
Hey Nicholas!
The binary writer won't do much for you
here, since it won't know how to lay out the strings.

I thought that LayoutKind.Sequential would have worked perfectly for that..
:O/

You are better of creating the structure, and having a specific class
what will format the output correctly to the file, and read the items from
the file (or rather, make it a stream, or a TextReader that you read
from).

Ok then, I'll give it a try.. I was a bit concerned about the execution
speed of such an approach. I'll test it against the APIs way for fun.

Thanks you very much for your help as always.
 
Zoury,

The LayoutKind.Sequential is used to indicate how the CLR should map the
structure to unmanaged memory when marshaling that structure to unmanaged
memory.

You aren't doing anything like that, so the attribute is unecessary (and
it will be the default behavior anyways if you don't specify otherwise).
 
The LayoutKind.Sequential is used to indicate how the CLR should map
the
structure to unmanaged memory when marshaling that structure to unmanaged
memory.

OK! I thought it meant that the CLR would keep the structure sequentially in
managed memory. :O/

thanks for the precision.
 
Back
Top