C # calls C + + platform invoke p/invoke struct--memory alignment, Union package "seven"

Source: Internet
Author: User

"1" Memory alignment

C + + code:

#pragma pack (push) #pragma pack (1) typedef struct _TESTSTRU2{INTIVAL;CHARCVAL;__INT64 llval;} TESTSTRU2; #pragma pack (POP)
Exportdll_api void Struct_packn (TestStru2 *pstru) {if (NULL = = Pstru) {return;} Pstru->ival = 1;pstru->cval = ' a ';p stru->llval = 2;wprintf (L "struct_packn \ n");}

C # code, specify pack to:

[StructLayout (layoutkind.sequential, Pack = 1, CharSet = charset.unicode)]public struct teststru2{public    int ival;< C2/>public sbyte cval;    public long  llval;}; [DllImport ("ExportDll.dll", CharSet = charset.unicode)]public static extern void Struct_packn (ref testStru2 Pstru);



the "2" union contains structural bodies

C + + code:

typedef Union _TESTSTRU4{INTIVALLOWER;INTIVALUPPER;STRUCT {__int64 lllocation;};} TestStru4;
Exportdll_api void Struct_union (TestStru4 *pstru) {if (NULL = = Pstru) {return;} Pstru->lllocation = 1024;wprintf (L "struct_union \ n");}

C # code:Defined asexplict, and show throughFieldOffsetSpecify memory Offset

[StructLayout (Layoutkind.explicit, charset=charset.unicode)]public struct teststru4{    [FieldOffset (0)]    Intivallower;    [FieldOffset (4)]    Intivalupper;    [FieldOffset (0)]           Long    lllocation;        }; [DllImport ("ExportDll.dll", CharSet = charset.unicode)]public static extern void Struct_union (ref testStru4 Pstru);


Cexportdll.teststru4 stru4 = new Cexportdll.teststru4 (); Cexportdll.struct_union (ref STRU4);

C # calls C + + platform invoke p/invoke struct--memory alignment, Union package "seven"

Related Article

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.