Manipulating structures and buffers

  • Thread starter Thread starter Neil W.
  • Start date Start date
N

Neil W.

I need to call some standard Windows APIs from C#, some of which require
structures and stuff. However, C# does not seem to include the concept of
clearing buffers or even of fixed sized buffers.

For example, how would I do something like this, which is very simple in
C/C++?

Thanks.

struct MYSTRUCT
{
unsigned char mychar;
char mystring[32];
int myint;
} mybuf;

memset(&mybuf,0,sizeof(MYSTRUCT));
mybuf.mychar = 0x12;
strcpy(mybuf.mystring,"abcdefghij");
mybuf.myint = 0x3456;
result = myapi(&mybuf);
 
I need to call some standard Windows APIs from C#, some of which require
structures and stuff.  However, C# does not seem to include the conceptof
clearing buffers or even of fixed sized buffers.

It does, actually. For one thing, there are fixed arrays (http://
msdn.microsoft.com/en-us/library/zycewsya.aspx):

fixed byte mystring[32];

but those are only valid in unsafe mode.

For P/Invoke purposes in particular (which is what you really need for
Win32 API), there are attributes which can be applied to a normal
array declaration to make it marshal as fixed-size buffer:

[MarshalAs(UnmanagedType.ByValArray, SizeConst=32)]
byte[] mystring;

See http://msdn.microsoft.com/en-us/library/z6cfh6e6.aspx for more
info.

To clear (fill with 0s) a managed array, use Array.Clear. To copy data
from one array to another, use Array.Copy, Array.CopyTo, or
Buffer.BlockCopy. Note that these all only work for managed arrays -
fixed arrays are treated by C# as pointers (i.e. for the "fixed"
declaration above), the actual type of mystring is "byte*", and there
are no standard FCL methods to deal with those. So if you use "fixed",
you'll either have to use WinAPI for memory ops as well, or write your
own.
 
Back
Top