1

I am reading a code in C#, and I am trying to understand a particular part of it. I am having trouble understanding it and I would appreciate if someone can explain that particular part to me.

First, there is a class

 [StructLayout(LayoutKind.Sequential, Pack = 2)]
        internal class SP_DEVICE_INTERFACE_DETAIL_DATA
        {
            internal int cbSize;
            internal short devicePath;
        }

then using the SetupDiGetDeviceInterfaceDetail function we get an IntPtr called buffer as in

SetupDiGetDeviceInterfaceDetail(_deviceInfoSet, interfaceData, buffer ,size, ref size, devData)

therefore now buffer is a pointer to an SP_DEVICE_INTERFACE_DETAIL_DATA to receive information about an interface. (I am assuming that this points to a class like the one above.

From now, it is the part that I get confused. We have

var strPtr = new IntPtr(buffer.ToInt64() + 4);
string devicePath =  Marshal.PtrToStringAuto(strPtr); 

So I am guessing that now strPtr points to the place where buffer points as a 64 bit integer. But then PtrToStringAuto is applied to "allocate a managed string and copy all characters to the first null character".. and I ask myself, what characters?? I thought all these pointers pointed to a class, not a string...

What am I overlooking?

KansaiRobot
  • 7,564
  • 11
  • 71
  • 150
  • The declaration is incorrect, devicePath is a string, not a short. And it requires CharSet=Unicode. The string behaves like MarshalAs(UnmanagedType.ByValStr, SizeConst=???). The ??? is the tricky problem, the struct is as large as needed to store the string content. The easy way to do it is to just pick a large number, like 1024, so any device path ought to fit. The hard way is to do it is the way it was designed, call SetupDiGetDeviceInterfaceDetail() twice with the first call designed to let it tell you how much memory is required. Requires marshaling by hand, so favor the easy way. – Hans Passant Feb 20 '18 at 10:40
  • As you can see from my comment on the duplicate, I already read that one. This question is not a duplicate because it is asking for explanation on how the last two statements work, not on what to do. If anything this is a follow up to that question because although i understand SetuoDiGetDeviceInterfaceDetail, I don't understand what follows next – KansaiRobot Feb 20 '18 at 14:46

0 Answers0