Convert to C # Call Windows API functions

Source: Internet
Author: User

API functions are used to construct windws applications.ProgramEvery kind of Windows application development tool. The underlying functions provided by the tool call Windows API functions indirectly or directly, generally, interfaces for calling windowsapi functions are provided, that is, they can call dynamic connection libraries. Visual C # can call the API functions of the dynamic link library like other development tools .. The net framework itself provides such a service that allowsCodeCall non-governed functions implemented in the dynamic link library, including Windows API functions provided by the operating system. It can locate and call the output function, and organize its parameters (integer, string type, array, and structure) to span the interoperability boundary as needed.

The following uses C # as an example to briefly introduce the basic process of calling an API:
Dynamic library function declaration
The function of the dynamic link library must be declared before use. Compared with VB, C # function declaration is even more difficult. The former can be directly used after being pasted through the API viewer, the latter requires extra parameter changes.

The function declaration part of the dynamic link library is generally composed of the following two parts: one is the function name or index number, and the other is the file name of the dynamic link library.
For example, if you want to call the MessageBox function in user32.dll, you must specify the function name messageboxa or messageboxw, and the library name user32.dll, we know that Win32 API generally has two versions for each function involving strings and characters, the ANSI version of single-byte characters and the Unicode version of double-byte characters.

The following is an example of calling an API function:
[Dllimport ("kernel32.dll", entrypoint = "movefilew", setlasterror = true,
Charset = charset. Unicode, exactspelling = true,
Callingconvention = callingconvention. stdcall)]
Public static extern bool movefile (string SRC, string DST );

The entry point entrypoint identifies the function's entry position in the dynamic link library. In a governed project, the original name and serial number entry point of the target function not only identifies a function that spans the interoperability boundary. You can also map the entry point to a different name, that is, rename the function. Renaming can bring various conveniences to function calling. by renaming, on the one hand, we don't have to worry about the case sensitivity of the function, and it can also ensure that it is consistent with the existing naming rules, allows functions with different parameter types to coexist. More importantly, it simplifies calls to ANSI and Unicode versions. Charset is used to identify the Unicode or ANSI version used for function calls. exactspelling = false tells the compiler to decide whether to use Unicode or ANSI. For other parameters, see the msdn online help.

In C #, you can declare a Dynamic Linked Library Function in the entrypoint field by name and serial number. If the function name used in the method definition is the same as the DLL entry point, you do not need to display the declaration function in the entrypoint field. Otherwise, you must use the following attribute format to indicate a name and serial number.

[Dllimport ("dllname", entrypoint = "functionname")]
[Dllimport ("dllname", entrypoint = "#123")]
It is worth noting that you must add "#" before the number
The following is an example of replacing the MessageBox name with msgbox:
[C #]
Using system. runtime. interopservices;

Public class Win32 {
[Dllimport ("user32.dll", entrypoint = "MessageBox")]
Public static extern int msgbox (INT hwnd, string text, string caption, uint type );
}
Many governed Dynamic Linked Library functions expect you to pass a complex parameter type to the function, such as a user-defined structure type member or a class member defined by the governed code, in this case, you must provide additional information to format this type to maintain the original layout and alignment of the parameter.

C # provides a structlayoutattribute class through which you can define your own formatting type. In the governed code, the formatting type is a structure or class member described by structlayoutattribute, it ensures the expected layout information of its internal members. There are three layout options:

Layout options
Description
Layoutkind. Automatic
To improve efficiency, the running state can be reordered by type members.
Note: never use this option to call uncontrolled Dynamic Linked Library functions.
Layoutkind. Explicit
Sort type members by fieldoffset attribute for each domain
Layoutkind. Sequential
Sort the type members in the memory that are not under the jurisdiction of the type definition.
Transfer Structure Member
The following example shows how to define a vertex and a rectangle type in the governed code and pass it as a parameter to the ptinrect function in the user32.dll library,
The ungoverned prototype of a function is declared as follows:
Bool ptinrect (const rect * LPRC, point pt );
Note that you must pass the rect structure parameter through reference, because the function requires a rect structure pointer.
[C #]
Using system. runtime. interopservices;

[Structlayout (layoutkind. Sequential)]
Public struct point {
Public int X;
Public int y;
}

[Structlayout (layoutkind. Explicit]
Public struct rect {
[Fieldoffset (0)] public int left;
[Fieldoffset (4)] public int top;
[Fieldoffset (8)] public int right;
[Fieldoffset (12)] public int bottom;
}

Class WIN32API {
[Dllimport ("user32.dll")]
Public static extern bool ptinrect (ref rect R, point P );
}
Similarly, you can call the getsysteminfo function to obtain system information:
? Using system. runtime. interopservices;
[Structlayout (layoutkind. Sequential)]
Public struct system_info {
Public uint dwoemid;
Public uint dwpagesize;
Public uint lpminimumapplicationaddress;
Public uint lpmaximumapplicationaddress;
Public uint dwactiveprocessormask;
Public uint dwnumberofprocessors;
Public uint dwprocessortype;
Public uint dwallocationgranularity;
Public uint dwprocessorlevel;
Public uint dwprocessorrevision;
}

 

[Dllimport ("Kernel32")]
Static extern void getsysteminfo (ref system_info psi );

System_info psi = new system_info ();
Getsysteminfo (ref psi );

Transfer of Class Members
Similarly, as long as the class has a fixed class member layout, you can pass a class member to an uncontrolled Dynamic Linked Library function, the following example shows how to pass a sequential sequence-defined mysystemtime class to the getsystemtime function of user32.dll. The Calling rules of the function using C/C ++ are as follows:

Void getsystemtime (systemtime * systemtime );
Unlike the value type, the class always transmits parameters through reference.
[C #]
[Structlayout (layoutkind. Sequential)]
Public class mysystemtime {
Public ushort wyear;
Public ushort wmonth;
Public ushort wdayofweek;
Public ushort wday;
Public ushort whour;
Public ushort wminute;
Public ushort wsecond;
Public ushort wmilliseconds;
}
Class WIN32API {
[Dllimport ("user32.dll")]
Public static extern void getsystemtime (mysystemtime st );
}
Transfer of callback functions:
To call most Dynamic Linked Library functions from governed code, you only need to create a function definition and then call it. This process is very direct.
If a Dynamic Linked Library function requires a function pointer as a parameter, You need to perform the following steps:
First, you must refer to the documentation on this function to determine whether a callback is required for this function. Second, you must create a callback function in the governed code. Finally, you can pass the pointer to this function as a parameter to the DLL function ,.

Callback Function and Its Implementation:
Callback functions are often used when tasks need to be executed repeatedly, such as enumeration functions, such as enumfontfamilies (font enumeration), enumprinters (printer), and enumwindows (window enumeration) functions in Win32 APIs. the following uses window enumeration as an example to describe how to call the enumwindow function to traverse all windows in the system.

Perform the following steps:
1. Refer to the function declaration before implementing the call.
Bool enumwindows (wndenumproc lpenumfunc, lparmam iparam)
Obviously, this function requires a callback function address as a parameter.
2. create a governed callback function. The example is declared as a representative type (delegate), that is, the callback we call. It has two parameters: hwnd and lparam, the first parameter is a window handle, and the second parameter is defined by the application. Both parameters are integer.

When this callback function returns a non-zero value, it indicates that the execution is successful, and zero indicates that the operation fails. In this example, the value true is always returned for continuous enumeration.
3. Create an object (delegate) and pass it as a parameter to the enumwindows function. The platform automatically converts the representation to a callback format that can be recognized by the function.

[C #]
Using system;
Using system. runtime. interopservices;

Public Delegate bool callback (INT hwnd, int lparam );

Public class enumreportapp {

[Dllimport ("USER32")]
Public static extern int enumwindows (callback X, int y );

Public static void main ()
{
Callback mycallback = new callback (enumreportapp. Report );
Enumwindows (mycallback, 0 );
}

Public static bool report (INT hwnd, int lparam ){
Console. Write ("window handle is ");
Console. writeline (hwnd );
Return true;
}
}

Pointer type parameter transfer:
When calling Windows API functions, most functions use pointers to pass parameters. For a structure variable pointer, we use the above class and structure method to pass Parameters, sometimes we can use arrays to pass parameters.

The following function obtains the user name by calling GetUserName.
Bool GetUserName (
Lptstr lpbuffer, // User Name Buffer
Lpdword nsize // address pointer for storing the buffer size
);

[Dllimport ("advapi32.dll ",
Entrypoint = "getcomputername ",
Exactspelling = false,
Setlasterror = true)]
Static extern bool getcomputername (
[Financialas (unmanagedtype. lparray)] Byte [] lpbuffer,
[Financialas (unmanagedtype. lparray)] int32 [] nsize );
This function accepts two parameters: char * and int *, because you must allocate a string buffer to accept the string pointer. You can use the string class to replace this parameter type, of course, you can also declare a byte array to pass the ANSI string, or you can declare a long integer array with only one element, using the array name as the second parameter. The above functions can be called as follows:

Byte [] STR = new byte [20];
Int32 [] Len = new int32 [1];
Len [0] = 20;
Getcomputername (STR, Len );
MessageBox. Show (system. Text. encoding. ASCII. getstring (STR ));
Note that before using each method, you must add the following content to the file header:
Using system. runtime. interopservices;

// Certificate //--------------------------------------------------------------------------------------------------------------------------------------------------

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 is installed. in C: \ Program Files \ Microsoft Visual Studio. net \ frameworksdk \ samples \ technologies \ InterOP \ platforminvoke \ winapis \ CS directory contains a large number of API call examples.

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
****************** * **************************/
//. net class
[structlayout (layoutkind. sequential)]
public class osversioninfo
{< br> Public int osversioninfosize;
Public int majorversion;
Public int minorversion;
Public int buildnumber;
Public int platformid;

[financialas (unmanagedtype. byvaltstr, sizeconst = 128)]
Public String versionstring;
}< br> // or
//. net is declared as a structure
[structlayout (layoutkind. sequential)]
public struct osversioninfo2
{< br> 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 );

 

trackback: http://tb.blog.csdn.net/TrackBack.aspx? Postid = 1795838

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.