dotnet interop:
Hello,
I have some VS 2005 code in which I am setting up a C# declaration of the
Platform SDK header DEV_BROADCAST_PORT. That structure is declared in the
Platform SDK header file dbt.h as follows:
typedef struct _DEV_BROADCAST_PORT_A {
DWORD dbcp_size;
DWORD dbcp_devicetype;
DWORD dbcp_reserved;
char dbcp_name[1];
} DEV_BROADCAST_PORT_A, *PDEV_BROADCAST_PORT_A;
typedef struct _DEV_BROADCAST_PORT_W {
DWORD dbcp_size;
DWORD dbcp_devicetype;
DWORD dbcp_reserved;
wchar_t dbcp_name[1];
} DEV_BROADCAST_PORT_W, DBTFAR *PDEV_BROADCAST_PORT_W;
#ifdef UNICODE
typedef DEV_BROADCAST_PORT_W DEV_BROADCAST_PORT;
typedef PDEV_BROADCAST_PORT_W PDEV_BROADCAST_PORT;
#else
typedef DEV_BROADCAST_PORT_A DEV_BROADCAST_PORT;
typedef PDEV_BROADCAST_PORT_A PDEV_BROADCAST_PORT;
#endif
In my C# code, I am declaring this structure as follows:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct DEV_BROADCAST_PORT
{
public uint dbcp_size;
public uint dbcp_devicetype;
public uint dbcp_reserved;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)]
public string dbcp_name;
}
My question is: Is this the correct P/Invoke declaration? It seems to
work, but I'm confused as to why the string marshalling declaration of
"dbcp_name" is working. According to the documentation for
DEV_BROADCAST_PORT, dbcp_name is a pointer to a null-terminated string. When
I started writing the C# declaration, I initially set the SizeConst parameter
equal to 1, because that's the fixed-array size of the dbcp_name member as
declared in the SDK header file. Of course, that didn't quite work; I only
received the first character of the COM port name when I ran my code. So I
picked some arbitrary character length (512, in this case) and assigned that
to the SizeConst parameter, and now it works. But, I don't know why. Am I
doing this right? Is it OK to just pick some arbitrary character length, as
I did above?
--
Whitney Kew