Home >Backend Development >PHP Tutorial >Key points of C# calling windows api_PHP tutorial

Key points of C# calling windows api_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:07:52916browse

Key points of calling Windows API from C#

In the .Net Framework SDK documentation, the instructions for calling Windows API are scattered, and the more comprehensive one is for Visual Basic .net narrated. This article summarizes the key points of calling APIs in C# as follows. I hope it will be helpful to friends who have not used APIs in C#. In addition, if Visual Studio .net is installed, there are a large number of examples of calling APIs in the C:/Program Files/Microsoft Visual Studio .NET/FrameworkSDK/Samples/Technologies/Interop/PlatformInvoke/WinAPIs/CS directory.

1. Call format

Using System.Runtime.InteropServices; //Reference this namespace to simplify the following code

//Use the DllImportAttribute attribute to introduce the api function. Note that the empty method is 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

The public fields of the DllImportAttribute attribute are as follows:

 1. CallingConvention indicates the CallingConvention value used when passing method parameters to unmanaged implementations.

CallingConvention.Cdecl: The caller clears the stack. It enables you to call functions with varargs.

CallingConvention.StdCall: The callee clears the stack. It is the default convention for calling unmanaged functions from managed code.

 2. CharSet controls the name version of the calling function and indicates how to marshal String parameters 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 the unmanaged implementation. This also causes the letter "W" to be appended to the name of the DLL EntryPoint. If this field is set to Ansi, the string is converted to an ANSI string, appending the letter "A" to the name of the DLL EntryPoint. Most Win32 APIs use this convention of appending a "W" or "A". If CharSet is set to Auto, this conversion is platform-dependent (Unicode on Windows NT, Ansi on Windows 98). The default value for CharSet is Ansi. The CharSet field is also used to determine which version of the function will be imported from the specified DLL. The name matching rules for CharSet.Ansi and CharSet.Unicode are quite different. For Ansi, if the EntryPoint is set to "MyMethod" and it exists, "MyMethod" is returned. If "MyMethod" does not exist in the DLL but "MyMethodA" exists, "MyMethodA" is returned. The opposite is true for Unicode. If EntryPoint is set to "MyMethod" and it exists, returns "MyMethodW". If "MyMethodW" does not exist in the DLL, but "MyMethod" does, then "MyMethod" is returned. If you are using Auto, the matching rules are platform-dependent (Unicode on Windows NT, Ansi on Windows 98). If ExactSpelling is set to true, "MyMethod" is returned only if "MyMethod" exists in the DLL.

 3. EntryPoint indicates the name or serial number of the DLL entry point to be called.

If your method name does not want to be the same as the api function, 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 the name of the entry point in the unmanaged DLL should be modified to correspond to the CharSet value specified in the CharSet field. If true, the letter A is appended to the method name when the DllImportAttribute.CharSet field is set to the Ansi value of CharSet, and the letter W is appended to the method name when the DllImportAttribute.CharSet field is set to the Unicode value of CharSet. The default value for this field is false.

 5. PreserveSig indicates that the managed method signature should not be converted to return an HRESULT and may have an unmanaged signature with additional [out, retval] parameters corresponding to the return value.

 6. SetLastError instructs the callee to call Win32 API SetLastError before returning from the attributed method. true indicates that the caller will call SetLastError, default is false. The runtime marshaler will call GetLastError and cache the returned value to prevent it from being overwritten by other API calls. The user can retrieve the error code by calling GetLastWin32Error.

2. Parameter type:

1. Just use the corresponding numerical value.

 2. String pointer (api) -> string (.net)

 3. Handle (dWord) -> IntPtr

4. Structure -> Structure or class

In this case, you must first qualify the statement with the StructLayout attribute, for example:

// declared as class

 [ StructLayout( LayoutKind.Sequential )]

public class OSVersionInfo

 {

public int OSVersionInfoSize;

public int majorVersion;

public int minorVersion;

public int buildNumber;

public int platformId;

 [ MarshalAs( UnmanagedType.ByValTStr, SizeConst=128 )]

public String versionString;

 }

 // declared as struct

 [ StructLayout( LayoutKind.Sequential )]

public struct OSVersionInfo2

 {

public int OSVersionInfoSize;

public int majorVersion;

public int minorVersion;

public int buildNumber;

public int platformId;

 [ MarshalAs( UnmanagedType.ByValTStr, SizeConst=128 )]

public String versionString;

 }

MashalAs attribute: used to describe the marshaling format of fields, methods, or parameters. Attributes prefix parameters and specify the data types required by the target. For example, the following code marshals two arguments to the Windows API function String (LPStr) as data type long pointer:

 [MarshalAs(UnmanagedType.LPStr)]

String existingfile;

 [MarshalAs(UnmanagedType.LPStr)]

String newfile;

Note that when a structure is used as a parameter, the ref modifier must be added in front, otherwise an error will occur: the reference to the object does not specify an instance of the object.

 [ DllImport( "kernel32", EntryPoint="GetVersionEx" )]

public static extern bool GetVersionEx2( ref OSVersionInfo2 osvi );

 3. If the managed object is not referenced anywhere after calling platform invoke, the garbage collector may complete the managed object. This frees the resource and invalidates the handle, causing platform invoke calls to fail. Wrapping the handle with a HandleRef ensures that the managed object is not garbage collected until the platform invoke call completes.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/953963.htmlTechArticleThe key points of calling Windows API in C# In the .Net Framework SDK document, the instructions on calling Windows API are scattered, and The more comprehensive one is for Visual Basic .net. This article...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn