C # API call format and parameter types

A, call format
using System.Runtime.InteropServices; // this namespace references, simplified code behind
// DllImportAttribute used to introduce api function characteristic, note method declaration is empty, i.e. the method body is empty.
[The DllImport ( "User32.dll")]
public static extern ReturnType FunctionName (type arg1, arg2 type, ...);
and invoke other methods // call when no difference

is further illustrated characteristic field can be used, separated by commas, such as:
[the DllImport ( "kernel32", the EntryPoint = "the GetVersionEx")]
the DllImportAttribute common characteristic fields are as follows:
. 1, CallingConvention value indicating achieve CallingConvention delivery method parameters used to unmanaged.
CallingConvention.Cdecl: caller clean up the stack. It enables you to call a function with varargs.
CallingConvention.StdCall: callee clean up the stack. It is the default agreed to call an unmanaged function from managed code.
2, CharSet call control function indicating the name and version of how to marshal String parameter to the method.
This field is set to one CharSet value. If the field is set to CharSet Unicode, all the parameters passed to the string into Unicode characters are converted before unmanaged implementation. This also results in an additional letter "W" in the name of the DLL EntryPoint. If this field is set to Ansi, the string is converted to an ANSI string, while the additional letter "A" in the name of the DLL EntryPoint. Most Win32 API to use this additional "W" or "A" of the agreement. If the CharSet is set to Auto, then this conversion is platform-dependent (on Windows NT is Unicode, on Windows 98 as Ansi). The default CharSet value Ansi. CharSet field is also used to determine which version of the function specified DLL import from. CharSet.Ansi and CharSet.Unicode name matching rules very different. For Ansi, if the EntryPoint is set to "MyMethod" and it exists, "MyMethod" is returned. If the DLL is not "MyMethod", but there are "MyMethodA", then "MyMethodA" return. It is just the opposite for Unicode. If EntryPoint is set to "MyMethod" and it exists, "MyMethodW" is returned. If there is no "MyMethodW" DLL in, but there are "MyMethod", then "MyMethod" return. If you are using Auto, the matching rule is platform-dependent (on Windows NT is Unicode, on Windows 98 as Ansi). If ExactSpelling set to true, then return only when "MyMethod" presence "MyMethod" DLL in.


3, EntryPoint indicating DLL entry point name or number to be called.
If you do not want the same name as the method name and api function, it must be specified, for example:
[DllImport ( "user32.dll", the CharSet = "CharSet.Auto", EntryPoint = "MessageBox")]
public static extern int MsgBox ( the hWnd IntPtr, TXT String, String Caption, type int);


. 4, indicating whether it should change the name ExactSpelling unmanaged DLL entry point to specify the CharSet CharSet value corresponding field. If true, the field is set to Ansi when DllImportAttribute.CharSet CharSet value, the letter A is added to the name of the method, when the field is set to DllImportAttribute.CharSet CharSet Unicode value, an additional letter to the name of the method of W. The default value of this field is false.
5, PreserveSig indicating hosting method signature should not be converted into a return HRESULT, and there may be additional return values [out, retval] unmanaged signature corresponds to a parameter.
6, SetLastError indicating the caller attributes before returning from the method call Win32 API SetLastError. true indicate that the caller will call SetLastError, the default is false. Marshaler runtime calls GetLastError and cache the return value, which is invoked to prevent overwriting other API. The user can retrieve the error code by calling GetLastWin32Error.

Second, the parameter type:
1, with the corresponding value of the direct type can. (DWORD -> int, WORD -> Int16)
2, the API pointer type string -> .net in String
. 3, the API in the handle (dWord) -> .net in IntPtr
. 4, the structure of the API -> .net structural or class. Note that this case, with the first defining characteristic StructLayout class declaration structure or
the common language runtime using class data field StructLayoutAttribute control structure or managed in the physical layout of memory, i.e., structure type, or arranged in some way required. If you type is passed to unmanaged code to specify the layout, layout category Explicit control is important. With its constructor initializes a new instance of the value LayoutKind StructLayoutAttribute class. LayoutKind.Sequential used to force the members of the order in the order they appear in the layout.
LayoutKind.Explicit for controlling the precise location of each data member. Using Explicit, each member must FieldOffsetAttribute indication position this field types. Such as:
[the StructLayout (LayoutKind.Explicit, Size = 16, the 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 is)] public ushort wSecond;
[FieldOffset (14)] public ushort wMilliseconds;
}
the following is an example for the structure OSVERSIONINFO API, or the class definition to the structure in .net:
/ ****************** ****************************
* API defined in the original structure declaration
* OSVERSIONINFOA STRUCT
* dwOSVersionInfoSize DWORD?
* dwMajorVersion DWORD?
* dwMinorVersion DWORD?
dwBuildNumber DWORD *?
* dwPlatformId DWORD?
* szCSDVersion BYTE 128 dup (?)
* OSVERSIONINFOA ENDS
*
* OSVERSIONINFO equ <OSVERSIONINFOA>
*********************************************/


//.net中声明为类
[ 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;
}
//或者
//.net中声明为结构
[ StructLayout( LayoutKind.Sequential )]
public struct OSVersionInfo2
{
public int OSVersionInfoSize;
int majorVersion public;
public int minorVersion;
public int BuildNumber;
public int PlatformId;


[the MarshalAs (UnmanagedType.ByValTStr, SizeConst = 128)]
public String VersionString;
}

In this example used MashalAs characteristics, it is used to describe the field, method or parameter marshaling format. Prefix and use it as a parameter to specify the type of data desired target. For example, the following code two parameters as a data type long pointer to the string seal (LPStr) Windows API functions:
[the MarshalAs (UnmanagedType.LPStr)]
String existingfile;
[the MarshalAs (UnmanagedType.LPStr)]
String newfile;

Note structure as a parameter, the general in front of ref modifier to add, or an error: object reference not specified instance of the object.
[The DllImport ( "kernel32", the EntryPoint = "the GetVersionEx")]
public static extern BOOL GetVersionEx2 (REF OSVersionInfo2 osvi);

Reproduced in: https: //www.cnblogs.com/kevinGao/archive/2011/11/21/2270749.html

Guess you like

Origin blog.csdn.net/weixin_33971130/article/details/93052675