C # key points of Calling Windows APIs

Source: Internet
Author: User
Tags readfile
In the. NET Framework SDK documentation The API indicators 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 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.

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 (in Windows Unicode for NT, in Windows 98 is ANSI ). 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 rules are related to the platform (in Windows Unicode for NT, in Windows 98 is ANSI ). 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.
2. String pointer (API)-> string (. NET)
3. Handle (DWORD)-> intptr
4. Structure-> structure or Class
In this case, the structlayout feature should be used to limit the declaration, 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;

[Financialas (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;

[Financialas (unmanagedtype. byvaltstr, sizeconst = 128)]
Public String versionstring;
}
Mashalas features: used to describe the sending format of fields, methods, or parameters. Feature as the parameter prefix and specify the data type required by the target. For example, the following code blocks two parameters as long pointers of data types to WindowsString Of the API function (lpstr ):
[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. 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.
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, therefore, it may be recycled by the recycle bin before the platform call is completed. After the file stream handle is packaged with handleref, it can be 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 );

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.