Features of StructLayout

                                 Features of StructLayout


table of Contents

1. Blog introduction

2. Content

(1) Writing use cases

(2) Role

(3) Usage scenarios

3. Push

4. Conclusion

 


1. Blog introduction

       When I wrote the previous article about calling win32 API to obtain windows, I saw some StructLayout writing methods. At first, some did not understand the meaning of the writing methods very well. After a little inspection, this blog does a knowledge record.


2. Content

(1) Writing use cases

[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Auto)]
public class StringClass
{
    [FieldOffset(0)] public string str1; 
    [FieldOffset(1)] public string str2;
    [FieldOffset(2)] public string str3;
    [FieldOffset(3)] public string str4; 
    [FieldOffset(4)] public string str5;
}


[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class FileDlg
{
    public int structSize = 0;
    public IntPtr dlgOwner = IntPtr.Zero;
    public IntPtr instance = IntPtr.Zero;
    public String filter = null;
}

(2) Role

StructLayout can ensure that the layout of the incoming structure is consistent with the layout required by the target calling code

Parameters: LayoutKind

This parameter has two attributes, Sequential and Explicit. The Sequential parameter can ensure that the modified method or the attributes in the structure are passed in and called in order. Explicit can accurately locate the order of the attributes by [FieldOffset(0)].

Parameters: CharSet = CharSet.Auto

Encoding format

(3) Usage scenarios

        By default, .net will adjust the layout of managed objects because adjustments can save memory. But sometimes, we don’t want this automatic adjustment. The reason is that when we call win32api, the original api belongs to unmanaged code. The layout of the corresponding structure in these codes is certain, and the parameters we pass in must conform to the original Layout, at this time we can use StructLayout to ensure that the layout of the incoming structure is consistent with the layout required by the target calling code.


3. Push

Github:https://github.com/KingSun5


4. Conclusion

       If you feel that the blogger’s article is well written, you may wish to pay attention to the blogger and like the blog post. In addition, the ability of the blogger is limited. If there is any error in the article, you are welcome to comment and criticize.

       QQ exchange group: 806091680 (Chinar)

       This group was created by CSDN blogger Chinar, recommend it! I am also in the group!

  

Guess you like

Origin blog.csdn.net/Mr_Sun88/article/details/101323222