C # Calling the Essentials of Windows API _php tutorial

Source: Internet
Author: User

The essentials of calling the Windows API for C #


In the. NET Framework SDK documentation, instructions for invoking the Windows API are fragmented, and a little more comprehensive is about visual Basic. Net. This article brings together the main points of calling APIs in C # to help a friend who has not used the API in C #. Also, if you have Visual Studio. NET installed, in C:/Program files/microsoft Visual Studio. Net/frameworksdk/samples/technologies/interop There are a number of examples of API invocation in the/PLATFORMINVOKE/WINAPIS/CS directory.

First, call format

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

...

Using the DllImportAttribute attribute to introduce API functions, notice 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,...);

Call time is no different than calling other methods

The public fields of the DllImportAttribute feature are as follows:

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

CALLINGCONVENTION.CDECL: The caller cleans up the stack. It enables you to invoke a function that has varargs.

Callingconvention.stdcall: The callee cleans up 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 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 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, and the letter "A" is appended to the name of the DLL entrypoint. Most Win32 APIs Use this convention to append "W" or "a". If CharSet is set to Auto, this conversion is platform-related (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 very different. For Ansi, if EntryPoint is set to "MyMethod" and it exists, then "MyMethod" is returned. If there is no "MyMethod" in the DLL, but "Mymethoda" is present, then "Mymethoda" is returned. The opposite is true for Unicode. If EntryPoint is set to "MyMethod" and it exists, then "Mymethodw" is returned. If "Mymethodw" is not present in the DLL, but "MyMethod" is present, then "MyMethod" is returned. If you are using Auto, the matching rules are platform-related (Unicode on Windows NT, Ansi on Windows 98). If ExactSpelling is set to True, "MyMethod" is returned only if "MyMethod" is present in the DLL.

3. entrypoint indicates the name or ordinal of the DLL entry point to invoke.

If your method name does not want to have the same name as the API function, be sure to 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, when the DllImportAttribute.CharSet field is set to CharSet Ansi value, the letter A is appended to the method name, and when the DllImportAttribute.CharSet field is set to CharSet U When the value is Nicode, the letter W is appended to the name of the method. The default value for this field is false.

5. PreserveSig indicates that the managed method signature should not be converted to a return HRESULT, and there may be an unmanaged signature that corresponds to the return value of the attached [out, retval] parameter.

6. SetLastError indicates that the callee will call the Win32 API SetLastError before returning from the attributed method. True indicates that the caller will call SetLastError, which defaults to false. The runtime marshaler calls GetLastError and caches the returned value in case it is overridden by another API call. The user can retrieve the error code by calling GetLastWin32Error.

Second, the parameter type:

1, numerical type directly with the corresponding can be.

2, string pointer (API)-string (. net)

3, handle (DWord), IntPtr

4. Structure----structure or class

In this case, you would first qualify the declaration 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: The marshaling format used to describe a field, method, or parameter. attribute as a parameter prefix and specify the data type that the target requires. For example, the following code marshals a string of two parameters to a Windows API function as a long pointer to a data type (LPSTR):

[MarshalAs (UNMANAGEDTYPE.LPSTR)]

String Existingfile;

[MarshalAs (UNMANAGEDTYPE.LPSTR)]

String NewFile;

Note that when a struct is a parameter, it is generally preceded by a ref modifier, otherwise an error occurs: The object's reference does not specify an instance of the object.

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

public static extern bool GetVersionEx2 (ref OSVersionInfo2 OSVI);

Third, if the managed object is not referenced anywhere after the call to platform invoke, the garbage collector may complete the managed object. This frees the resource and invalidates the handle, causing the platform invoke call to fail. Wrapping a handle with handleref guarantees that the managed object will not be garbage collected until the platform invoke call completes.

http://www.bkjia.com/PHPjc/953963.html www.bkjia.com true http://www.bkjia.com/PHPjc/953963.html techarticle the essentials of calling the Windows API in C # in the. NET Framework SDK documentation, the instructions for invoking the Windows API are fragmented, and a slightly more comprehensive one is for visual Basic. Net. This 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.