I am trying to do something like this in C#. I found out how to call Win32 methods from C# using P/Invoke from this link. However I met some difficulties in implementing P/Invoke.
For example, one of the methods that I would like to access is PdhOpenQuery,
signature:
PDH_STATUS PdhOpenQuery(
__in LPCTSTR szDataSource,
__in DWORD_PTR dwUserData,
__out PDH_HQUERY *phQuery
);
I figure the corresponding C# declaration should be something like this
[DllImport("Pdh.dll")]
static extern PDH_STATUS PdhOpenQuery(LPCTSTR szDataSource,
DWORD_PTR dwUserData, out PDH_HQUERY *phQuery);
My questions:
What is LPCTSTR, and to what data type does it map in C#?
How to map a pointer type DWORD_PTR? The pinvoke article says DWORD maps to UInt32, but how about pointers?
I think PDH_STATUS and PDH_HQUERY are specific struct to the library (I’m not sure yet). how do I map these?
What is the correct method declaration, and how do you call it correctly?
LPCTSTRis a typedef forconst TCHAR*.TCHARis an attempt to abstract away the fact that the Windows API exists in both “ANSI” (charstrings in a locale-specific encoding) and “Unicode” (UTF-16) versions. There is no actualPdhOpenQueryfunction; there is aPdhOpenQueryAfunction that takes an ANSI string and aPdhOpenQueryWfunction that takes a UTF-16 string.C# uses UTF-16 strings, so you’ll want to prefer the “W” version of these functions. Use
PdhOpenQueryW. Then the first parameter has C++ typeconst wchar_t*. The C# type is[MarshalAs(UnmanagedType.LPWStr)] string.DWORD_PTRisn’t a pointer. It’s an unsigned integer big enough to hold a pointer. The equivalent C# type isSystem.UIntPtr.PDH_STATUSappears to be just anint.PDH_HQUERYis a pointer to a handle (another pointer), but you can just pretend it’s an integer and useIntPtr.Putting it all together, your declaration should be: