The string has no links in the C # structure with layout

I have a structure

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SERVER_USB_DEVICE
{
    USB_HWID usbHWID;
    byte status;
    bool bExcludeDevice;
    bool bSharedManually;
    ulong ulDeviceId;
    ulong ulClientAddr;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
    string usbDeviceDescr;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
    string locationInfo;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
    string nickName;
}

When I pass it to win32 dll functions as below:

[DllImport ("abc.dll", EntryPoint="EnumDevices", CharSet=CharSet.Ansi)]
public static extern bool EnumDevices(IntPtr lpUsbDevices,
                                      ref  ulong pulBufferSize, 
                                      IntPtr lpES);

I get the missing text in the string elements of the structure.

Suppose SERVER_USB_DEVICE.usbDeviceDescr contains the value "Mass Storage Device", which is incorrect, it must contain the value "USB Mass Storage Device"

What is wrong with the code?

+3
source share
4 answers

I actually made a small mistake here. ulong - 8 bytes in C #, where 4 bytes in C ++ (as we all know). converting ulong to uint solved the problem.

+1
source

Try ByValTStrinsteadByValArray

0
source

, , usbDeviceDescr (status, bExcludeDevice, bSharedManually, ulDeviceId ulClientAddr), ? , USB_HWID, 4 ?

0
source

You can look at the structure in a byte array to make sure everything is aligned correctly. Try the following:

int size = Marshal.SizeOf(typeof(SERVER_USB_DEVICE));
byte[] buffer1 = new byte[size];
SERVER_USB_DEVICE[] buffer2 = new SERVER_USB_DEVICE[1];
// put instance of SERVER_USB_DEVICE into buffer2
Buffer.BlockCopy(buffer2, 0, buffer1, 0, size);
0
source

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


All Articles