DWORD and VARTYPE equivalent in c#

2019-07-24 17:24发布

问题:

I am using an API which contains following methods:

BOOL GetItemPropertyDescription (HANDLE hConnect, int PropertyIndex, DWORD *pPropertyID, VARTYPE *pVT, BYTE *pDescr, int BufSize);
BOOL ReadPropertyValue (HANDLE hConnect, LPCSTR Itemname, DWORD PropertyID, VARIANT *pValue);

What will be equivalent in c#?

What is the meaning of DWORD, VARTYPE, VARIANT datatypes?

回答1:

There is a fairly complete table here at Table 1. Try looking.

DWORD is uint
VARTYPE is an ushort (but you have a ref ushort there) 
        or much better a VarEnum (but you have a ref VarEnum there)
        (VarEnum is defined under System.Runtime.InteropServices)
VARIANT is object (but you have a ref object there)

There is an article here on the marshaling of VARIANT: http://blogs.msdn.com/b/adam_nathan/archive/2003/04/24/56642.aspx

The exact PInvoke is complex to write, it depends on the direction of the parameters and their exact specification. Is pPropertyID a pointer to a single DWORD, or is a pointer to the first DWORD of an "array"? And who "fills" the value pointed at, the caller or the callee or both? The same for all the other pointers.

Technically all/part of the refs could be out if they are filled by the callee.

By the name of the methods, their pinvoke could be:

[DllImport("YourDll.dll")]
//[return: MarshalAs(UnmanagedType.Bool)] // This line is optional, and it's implicit
bool GetItemPropertyDescription(IntPtr hConnect, 
                                int propertyIndex, 
                                out uint pPropertyID, 
                                out VarEnum pVT, 
                                out IntPtr pDescr, 
                                int bufSize);

[DllImport("YourDll.dll", CharSet = CharSet.Ansi)]
//[return: MarshalAs(UnmanagedType.Bool)] // This line is optional, and it's implicit
bool ReadPropertyValue(IntPtr hConnect, 
                       string itemName, 
                       uint propertyID, 
                       out object pValue);