Define declarative structures or classes with structlayout features

Source: Internet
Author: User

1. Use the structlayout feature to limit the declared structure or Class
The Common Language Runtime library uses structlayoutattribute to control the physical layout of data fields of a class or structure in the managed memory, that is, classes or structures need to be arranged in some way. If you want to pass the class to the unmanaged code that requires the specified layout, it is important to explicitly control the class layout. Its constructor uses the layoutkind value to initialize a new instance of the structlayoutattribute class. Layoutkind. Sequential is used to force the members to layout in the order they appear.
Layoutkind. Explicit is used to control the exact location of each data member. With explicit, each member must use fieldoffsetattribute to indicate the position of this field in the type. For example:

View plaincopy to clipboardprint?
  1. [Structlayout (layoutkind. explicit, size = 16, charset = charset. ANSI)]
  2. Public ClassMysystemtime
  3. {
  4. [Fieldoffset (0)]Public UshortWyear;
  5. [Fieldoffset (2)]Public UshortWmonth;
  6. [Fieldoffset (4)]Public UshortWdayofweek;
  7. [Fieldoffset (6)]Public UshortWday;
  8. [Fieldoffset (8)]Public UshortWhour;
  9. [Fieldoffset (10)]Public UshortWminute;
  10. [Fieldoffset (12)]Public UshortWsecond;
  11. [Fieldoffset (14)]Public UshortWmilliseconds;
  12. }

[Structlayout (layoutkind. explicit, size = 16, charset = charset. ANSI)] <br/> public class mysystemtime <br/> {<br/> [fieldoffset (0)] public ushort wyear; <br/> [fieldoffset (2)] public ushort wmonth; <br/> [fieldoffset (4)] public ushort wdayofweek; <br/> [fieldoffset (6)] public ushort wday; <br/> [fieldoffset (8)] public ushort whour; <br/> [fieldoffset (10)] public ushort wminute; <br/> [fieldoffset (12)] public ushort wsecond; <br/> [fieldoffset (14)] public ushort wmilliseconds; <br/>}
The following is an example of defining the corresponding class or structure in. net for the osversioninfo structure in the API:
/*************************************** *******
* Define the original structure declaration in the API
* Osversioninfoa struct
* Dwosversioninfosize DWORD?
* Dwmajorversion DWORD?
* Dwminorversion DWORD?
* Dwbuildnumber DWORD?
* Dwplatformid DWORD?
* Szcsdversion byte 128 DUP (?)
* Osversioninfoa ends
*
* Osversioninfo equ <osversioninfoa>
**************************************** *****/
//. NET is declared as a class

View plaincopy to clipboardprint?
  1. [Structlayout (layoutkind. Sequential)]
  2. Public ClassOsversioninfo
  3. {
  4. Public IntOsversioninfosize;
  5. Public IntMajorversion;
  6. Public IntMinorversion;
  7. Public IntBuildnumber;
  8. Public IntPlatformid;
  9. [Financialas (unmanagedtype. byvaltstr, sizeconst = 128)]
  10. PublicString versionstring;
  11. }

[Structlayout (layoutkind. sequential)] <br/> public class osversioninfo <br/>{< br/> Public int osversioninfosize; <br/> Public int majorversion; <br/> Public int minorversion; <br/> Public int buildnumber; <br/> Public int platformid; <br/> [financialas (unmanagedtype. byvaltstr, sizeconst = 128)] <br/> Public String versionstring; <br/>}
// Or
// The Declaration in. Net is a structure

View plaincopy to clipboardprint?
  1. [Structlayout (layoutkind. Sequential)]
  2. Public StructOsversioninfo2
  3. {
  4. Public IntOsversioninfosize;
  5. Public IntMajorversion;
  6. Public IntMinorversion;
  7. Public IntBuildnumber;
  8. Public IntPlatformid;
  9. [Financialas (unmanagedtype. byvaltstr, sizeconst = 128)]
  10. PublicString versionstring;
  11. }

[Structlayout (layoutkind. sequential)] <br/> public struct osversioninfo2 <br/>{< br/> Public int osversioninfosize; <br/> Public int majorversion; <br/> Public int minorversion; <br/> Public int buildnumber; <br/> Public int platformid; <br/> [financialas (unmanagedtype. byvaltstr, sizeconst = 128)] <br/> Public String versionstring; <br/>}
In this example, the mashalas feature is used to describe the sending format of fields, methods, or parameters. Use it as the parameter prefix and specify the data type required by the target. For example, the following code uses two parameters as the long pointer of the Data Type to block the string (lpstr) sent to the Windows API function ):
[Financialas (unmanagedtype. lpstr)]
String existingfile;
[Financialas (unmanagedtype. lpstr)]
String newfile;
Note that when the structure is used as a parameter, the ref modifier must be added before. Otherwise, an error occurs: the object reference does not include an instance of the specified object.

View plaincopy to clipboardprint?
  1. [Dllimport ("Kernel32", entrypoint = "getversionex")]
  2. Public Static Extern BoolGetversionex2 (RefOsversioninfo2 osvi );

Ii. structlayout features

The Common Language Runtime library uses structlayoutattribute to control the physical layout of data fields of a class or structure in the managed memory, that is, the class or structure needs to be arranged in a certain way. If you want to pass the class to the unmanaged code that requires the specified layout, it is important to explicitly control the class layout. Its constructor uses the layoutkind value to initialize a new instance of the structlayoutattribute class. Layoutkind. Sequential is used to force members to be laid out in the order they appear.

The structlayout feature allows us to control the arrangement of elements in the structure statement block in the memory, and how the runtime arranges these elements when these elements are passed to the external DLL. The order of members in the Visual Basic Structure in the memory is arranged in the order they appear in the source code, although the compiler can freely Insert the padding byte to arrange these Members, in this way, the 16-bit value is aligned with the subboundary, and the 32-bit value is aligned with the double-character boundary.

This sort (uncompressed layout) provides the best performance.

In Visual Basic 6, the user-defined structure is not compressed, and we cannot change this default setting. This setting can be changed in VB. NET, and the location of each structure member can be precisely controlled through the system. runtime. interopservices. structlayout feature.
System. runtime. interopservices. structlayout allows structlayout. Auto structlayout. Sequential structlayout. explicit.
1. Sequential: sequential layout, such
Struct S1
{
Int;
Int B;
}
By default, A is first arranged in the memory and then B.
That is, if you can get the address of a, and the address of B, the difference is an int type length, 4 bytes
[Structlayout (layoutkind. Sequential)]
Struct S1
{
Int;
Int B;
}
This is the same as the previous one, because the default memory arrangement is sequential, that is, sequential arrangement by members.
2. explicit, precise Layout
You need to use fieldoffset () to set the location of each member.
In this way, the function of a public body similar to C can be implemented.
[Structlayout (layoutkind. explicit)]
Struct S1
{
[Fieldoffset (0)]
Int;
[Fieldoffset (0)]
Int B;
}
In this way, A and B are in the same memory address.

Structlayout supports three additional fields: charset, pack, and size.
· Charset defines the arrangement of string members in the structure when the structure is passed to the DLL. It can be UNICODE, ANSI, or auto.
The default value is auto. In Win NT/2000/XP, the strings are arranged by Unicode strings, and in Win 95/98/Me, the strings are arranged by ANSI strings.
· Pack defines the encapsulation size of the structure. It can be 1, 2, 4, 8, 16, 32, 64, 128, or a special value of 0. The special value 0 indicates the default compression size of the current operating platform.

[Structlayout (layoutkind. Sequential, charset = charset. ANSI)]
Public struct list_open
{
Public int dwserverid;
Public int dwlistid;
Public System. uint16 wrecordsize;
Public System. uint16 wdummy;
Public int dwfilesize;
Public int dwtotalrecs;
Public ns_prefetchlist sprefetch;
[Financialas (unmanagedtype. byvaltstr, sizeconst = 24)]
Public String szsrcmach;
[Financialas (unmanagedtype. byvaltstr, sizeconst = 24)]
Public String szsrccomp;
}

In this exampleMashalas featuresIt is used to describe the sending format of fields, methods, or parameters. Use it as the parameter prefix and specify the data type required by the target.
For example, the following code uses two parameters as the long pointer of the Data Type to block the string (lpstr) sent to the Windows API function ):
[Financialas (unmanagedtype. lpstr)]
String existingfile;
[Financialas (unmanagedtype. lpstr)]
String newfile;
Note that when the structure is used as a parameter, the ref modifier must be added before. Otherwise, an error occurs: the object reference does not include an instance of the specified object.
[Dllimport ("Kernel32", entrypoint = "getversionex")]
Public static extern bool getversionex2 (ref osversioninfo2 osvi );

Original article: http://www.cnblogs.com/JessieDong/archive/2009/07/21/1527553.html

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.