Passing strings / arrays inside structures between C ++ / C #

I am passing a structure from C # to C ++.

C # code:

[StructLayout(LayoutKind.Sequential, Pack = 8)]
public struct Data
{
[MarshalAs(UnmanagedType.U4)]
public int number;

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
public int[] array;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)]
public string buffer;
}

C ++ Code:

struct Data
{
public:
    int number;
    int array[5];
    char buffer[512];
    //char *buffer;
};

The above method is working fine. But instead, if I use pointers to process data in C++, I get an error like:

Unhandled exception: System.AccessViolationException: attempt to read or write protected memory

struct Data
{
public:
    int number;
    int *array;
    char *buffer;
};

Why can't I handle pointers here? Is handling this case through pointers beneficial?

+4
source share
2 answers

The problem is how your data is represented in memory.

Suppose you have an instance of a C # structure that marshals unmanaged code or even a file.

[StructLayout(LayoutKind.Sequential, Pack = 8)]
public struct Data
{
[MarshalAs(UnmanagedType.U4)]
public int number = 5;

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
public int[] array = {0, 1, 2, 3, 4};

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)]

public string buffer = "Happy new Year";
}

( ):

05 00 00 00 00 00 00 00
01 00 00 00 02 00 00 00
03 00 00 00 04 00 00 00
00 48 00 61 00 70 00 70 
00 79 00 20 00 6E 00 65 
00 77 00 20 00 59 00 65 
00 61 00 72

"05 00 00 00", "5" "". ( , , Intel - LittleEndian, . Endiannes )

"00 00 00 00" = 0, "01 00 00 00" = 1, "02 00 00 00" = 2, "03 00 00 00" = 3, "04 00 00 00" = 4 "array".

"buffer" :

"00 48" = H
"00 61" = a
"00 70" = p
"00 70" = p
"00 79" = y
"00 20" = <space>
"00 6E" = n
"00 65" = e
"00 77" = w
"00 20" = <space>
"00 59" = Y
"00 65" = e
"00 61" = a
"00 72" = r

, .NET Unicode . .

++

struct Data
{
public:
    int number;
    int array[5];
    char buffer[512];
    //char *buffer;
};

sizeof (int) 4. , "number" = "05 00 00 00", . [0], 1, [2], [3], [4] "00 00 00 00" = 0, "01 00 00 00" = 1, "02 00 00 00" = 2, "03 00 00 00" = 3, "04 00 00 00" = 4. [512]. ++ sizeof (char) == 1. char, ASCII . wchar_t, Unicode.

struct Data
{
public:
    int number;
    int *array;
    char *buffer;
};

, . 32- (win32) "" "00 00 00 00" (4 ) "buffer" "01 00 00 00".

64- (win64) "" "00 00 00 00 01 00 00 00" (8 ), "02 00 00 00 03 00 00 00".

- , , , . , .

+1

, . , int char ( sizeof(void*) ) , int. , (.. new delete[]).

+1

Source: https://habr.com/ru/post/1621099/


All Articles