Key Points of Calling Windows API in C #

Source: Internet
Author: User

In the. Net Framework SDK documentation, the instructions for calling Windows APIs are scattered, and a little more comprehensive is about Visual Basic. net. In this article, the main points of calling APIs in C # are summarized as follows, hoping to help those who have not used APIs in C. In addition, if Visual Studio. net is installed, there are a large number of API calling examples in the C: Program FilesMicrosoft Visual Studio. NETFrameworkSDKSamplesTechnologiesInteropPlatformInvokeWinAPIsCS directory.
I. Call format
Using System. Runtime. InteropServices; // reference this namespace to simplify the subsequent Code
...
// Use the DllImportAttribute feature to introduce api functions. Note that empty methods are declared, that is, the method body is empty.
[DllImport ("user32.dll")]
Public static extern ReturnType FunctionName (type arg1, type arg2 ,...);
// There is no difference between calling and calling other methods


You can use fields to further describe features and separate them with commas, for example:
[DllImport ("kernel32", EntryPoint = "GetVersionEx")]
The common fields of the DllImportAttribute feature are as follows:
1. CallingConvention indicates the CallingConvention value used to pass method parameters to an unmanaged implementation.
CallingConvention. Cdecl: The caller clears the stack. It enables you to call functions with varargs.
CallingConvention. StdCall: the called party clears the stack. It is the default convention for calling unmanaged functions from managed code.
2. CharSet controls the name version of the called function and indicates how to mail the String parameter to the method.
This field is set to one of the CharSet values. If the CharSet field is set to Unicode, all string parameters are converted to Unicode characters before being passed to an unmanaged implementation. This also causes the name of the DLL EntryPoint to be appended with the letter "W ". If this field is set to Ansi, the string is converted to an ANSI string and the name of the DLL EntryPoint is appended with the letter "". Most Win32 APIs use this APPEND "W" or "A" convention. If CharSet is set to Auto, the conversion is platform-related (Unicode on Windows NT and Ansi on Windows 98 ). The default value of CharSet is Ansi. The CharSet field is also used to determine which function version will be imported from the specified DLL. The name matching rules for CharSet. Ansi and CharSet. Unicode are very different. For Ansi, if EntryPoint is set to "MyMethod" and it exists, "MyMethod" is returned ". If the DLL does not contain "MyMethod", but "MyMethodA" exists, "MyMethodA" is returned ". The opposite is true for Unicode. If you set EntryPoint to "MyMethod" and it exists, "MyMethodW" is returned ". If "MyMethodW" does not exist in the DLL but "MyMethod" exists, "MyMethod" is returned ". If Auto is used, the matching rule is related to the platform (Unicode on Windows NT and Ansi on Windows 98 ). If ExactSpelling is set to true, "MyMethod" is returned only when "MyMethod" exists in the DLL ".


3. EntryPoint indicates the name or serial number of the DLL entry point to be called.
If you do not want the method name to be the same as the api function name, you must specify this parameter. For example:
[DllImport ("user32.dll", CharSet = "CharSet. Auto", EntryPoint = "MessageBox")]
Public static extern int MsgBox (IntPtr hWnd, string txt, string caption, int type );


4. ExactSpelling indicates whether to modify the name of the entry point in the unmanaged DLL to correspond to the CharSet value specified in the CharSet field. If this parameter is set to true, the parameter is set to DllImportAttribute. when the CharSet field is set to the Ansi value of CharSet, append the letter A to the method name, when DllImportAttribute. when the CharSet field is set to the Unicode value of CharSet, W is appended to the method name. The default value of this field is false.
5. PreserveSig indicates that the signature of the managed method should not be converted to an unmanaged signature that returns HRESULT and may have an additional [out, retval] parameter corresponding to the returned value.
6. SetLastError indicates that the called party will call the Win32 API SetLastError before returning the property method. True indicates that the caller calls SetLastError. The default value is false. GetLastError will be called by the mail collector during runtime and the returned value will be cached to prevent it from being overwritten by other API calls. You can call GetLastWin32Error to retrieve the error code.






Ii. Parameter type:
1. You can use the corresponding numeric type directly. (DWORD-> int, WORD-> Int16)
2. string pointer type in API-> string in. net
3. Handle (dWord) in API> IntPtr in. net
4. Structure in API>. net structure or class. Note that in this case, the StructLayout feature should be used to limit the declared structure or Class
The Common Language Runtime library uses StructLayoutAttribute to control the physical layout of data fields of a class or structure in the managed memory, that is, the class or structure needs to be arranged in a certain way. If you want to pass the class to the unmanaged code that requires the specified layout, it is important to explicitly control the class layout. Its constructor uses the LayoutKind value to initialize a new instance of the StructLayoutAttribute class. LayoutKind. Sequential is used to force members to be laid out in the order they appear.
LayoutKind. Explicit is used to control the exact location of each data member. With Explicit, each member must use FieldOffsetAttribute to indicate the position of this field in the type. For example:
[StructLayout (LayoutKind. Explicit, Size = 16, CharSet = CharSet. Ansi)]
Public class MySystemTime
{
[FieldOffset (0)] public ushort wYear;
[FieldOffset (2)] public ushort wMonth;
[FieldOffset (4)] public ushort wDayOfWeek;
[FieldOffset (6)] public ushort wDay;
[FieldOffset (8)] public ushort wHour;
[FieldOffset (10)] public ushort wMinute;
[FieldOffset (12)] public ushort wSecond;
[FieldOffset (14)] public ushort wMilliseconds;
}
The following is an example of defining the corresponding class or structure in. net for the osversioninfo structure in the API:
/*************************************** *******
* Define the original structure declaration in the API
* OSVERSIONINFOA STRUCT
* DwOSVersionInfoSize DWORD?
* DwMajorVersion DWORD?
* DwMinorVersion DWORD?
* DwBuildNumber DWORD?
* DwPlatformId DWORD?
* SzCSDVersion BYTE 128 dup (?)
* OSVERSIONINFOA ENDS
*
* OSVERSIONINFO equ <OSVERSIONINFOA>
**************************************** *****/


//. Net is declared as a class
[StructLayout (LayoutKind. Sequential)]
Public class OSVersionInfo
{
Public int OSVersionInfoSize;
Public int majorVersion;
Public int minorVersion;
Public int buildNumber;
Public int platformId;


[Financialas (UnmanagedType. ByValTStr, SizeConst = 128)]
Public String versionString;
}
// Or
// The Declaration in. net is a structure
[StructLayout (LayoutKind. Sequential)]
Public struct OSVersionInfo2
{
Public int OSVersionInfoSize;
Public int majorVersion;
Public int minorVersion;
Public int buildNumber;
Public int platformId;


[Financialas (UnmanagedType. ByValTStr, SizeConst = 128)]
Public String versionString;
}


In this example, the MashalAs feature is used to describe the sending format of fields, methods, or parameters. Use it as the parameter prefix and specify the data type required by the target. For example, the following code uses two parameters as the long pointer of the Data Type to block the string (LPStr) sent to the Windows API function ):
[Financialas (UnmanagedType. LPStr)]
String existingfile;
[Financialas (UnmanagedType. LPStr)]
String newfile;


Note that when the structure is used as a parameter, the ref modifier must be added before. Otherwise, an error occurs: the object reference does not include an instance of the specified object.
[DllImport ("kernel32", EntryPoint = "GetVersionEx")]
Public static extern bool GetVersionEx2 (ref OSVersionInfo2 osvi );


3. How can we ensure that the platform with managed objects is successfully called?
If the hosted object is not referenced anywhere after the platform invoke is called, The Garbage Collector may complete the hosted object. This will release the resource and make the handle invalid, resulting in platform invoke call failure. Using HandleRef to wrap the handle ensures that the hosted object is not garbage collected before the platform's invoke call is complete.
For example:
FileStream fs = new FileStream ("a.txt", FileMode. Open );
StringBuilder buffer = new StringBuilder (5 );
Int read = 0;
ReadFile (fs. Handle, buffer, 5, out read, 0); // call the ReadFile function in the Win API
Because fs is a hosted object, it may be reclaimed by the spam Recycle Bin before the platform call is complete. After packaging the file stream handle with HandleRef, you can avoid being recycled by the garbage station:
[DllImport ("Kernel32.dll")]
Public static extern bool ReadFile (
HandleRef hndRef,
StringBuilder buffer,
Int numberOfBytesToRead,
Out int numberOfBytesRead,
Ref Overlapped flag );
......
......
FileStream fs = new FileStream ("HandleRef.txt", FileMode. Open );
HandleRef hr = new HandleRef (fs, fs. Handle );
StringBuilder buffer = new StringBuilder (5 );
Int read = 0;
// Platform invoke will hold reference to HandleRef until call ends
ReadFile (hr, buffer, 5, out read, 0 );

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.