Prev | Current Page 379 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

Consult your compiler documentation for the
most up-to-date information.
The next feature is another one that you may well never use??”but at the same time,
if you ever do, it??™s likely to make your life somewhat simpler.
7.6 Fixed-size buffers in unsafe code
When calling into native code with P/Invoke, it??™s not particularly unusual to find yourself
dealing with a structure that is defined to have a buffer of a particular length
within it. Prior to C# 2, such structures were difficult to handle directly, even with
unsafe code. Now, you can declare a buffer of the right size to be embedded directly
with the rest of the data for the structure.
This capability isn??™t just available for calling native code, although that is its primary
use. You could use it to easily populate a data structure directly corresponding to
a file format, for instance. The syntax is simple, and once again we??™ll demonstrate it
with an example. To create a field that embeds an array of 20 bytes within its enclosing
structure, you would use
fixed byte data[20];
This would allow data to be used as if it were a byte* (a pointer to byte data),
although the implementation used by the C# compiler is to create a new nested type
within the declaring type and apply the new FixedBuffer attribute to the variable
itself. The CLR then takes care of allocating the memory appropriately.


Pages:
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391