Main points of C # calling Windows API

Source: Internet
Author: User
Tags error code win32 visual studio

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

One, calling format

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

...

Using the DllImportAttribute attribute to introduce API functions, notice that the null 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 from calling other methods

The public fields for the DllImportAttribute attribute are as follows:

1, callingconvention indicates the CallingConvention value to use when passing method parameters to an unmanaged implementation.

CALLINGCONVENTION.CDECL: The caller cleans up the stack. It enables you to invoke functions that have varargs.

Callingconvention.stdcall: The caller 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 that appends "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, returns "MyMethod" if EntryPoint is set to "MyMethod" and it exists. Returns "Mymethoda" if there is no "MyMethod" in the DLL, but there is a "Mymethoda". The opposite is true for Unicode. Returns "Mymethodw" if EntryPoint is set to "MyMethod" and it exists. Returns "MyMethod" if "Mymethodw" is not present in the DLL, but "MyMethod" exists. 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" exists 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, appends the letter A to the method name when the DllImportAttribute.CharSet field is set to the Ansi value of CharSet, when the DllImportAttribute.CharSet field is set to CharSet U Nicode value, append the letter W 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 may have an unmanaged signature that corresponds to an additional [out, retval] parameter corresponding to the return value.

6. SetLastError instructs the callee to invoke Win32 API SetLastError before returning from the attributed method. True indicates that the caller will invoke SetLastError, which defaults to false. The runtime marshaler invokes GetLastError and caches the returned value in case it is overridden by other API calls. 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 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 required by the target. For example, the following code sends two parameters to the Windows API function string (LPSTR) as a long pointer to the data type:

[MarshalAs (UNMANAGEDTYPE.LPSTR)]

String Existingfile;

[MarshalAs (UNMANAGEDTYPE.LPSTR)]

String NewFile;

Note structure as a parameter, generally preceded by the ref modifier, otherwise there will be an error: 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 invoking 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. The HandleRef wrapper handle guarantees that the managed object will not be garbage collected until the platform invoke call completes.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.