"Reprint" C # DllImport system calls use the introduction of detailed managed code entrypoint

Source: Internet
Author: User
Tags hosting

1 Use of DllImport

Using System;

Using System.Runtime.InteropServices; Name space

Class Example

{

Import the MessageBox function of Win32 with DllImport

[DllImport ("user32.dll", CharSet = CharSet.Unicode)]

public static extern int MessageBox (IntPtr hWnd, string text, string caption, uint type);

method is declared as static. This is required by the P/invoke method because there is no//consistent instance concept in the Windows API. Next, notice that the method is marked as extern. This is a hint to the compiler that the method is implemented through a function exported from a DLL, so there is no need to provide a method body.

static void Main ()

{

Call the MessageBox function using platform invoke.

MessageBox (new IntPtr (0), "Hello world!", "Hello Dialog", 0);

}

}

Using unmanaged DLL functions is not difficult, and we can learn more about the meaning of the above code. First, what is managed code and what is unmanaged code. Then we will explain in detail the usage of DllImport and the meanings of each field.

2 Managed codes (managed code)

The core of the. NET Framework is the execution environment of its runtime, known as the Common Language runtime (CLR) or. NET Runtime. Code that is typically run under the control of the CLR is called Managed code (managed).

Code that is executed by the runtime environment (not directly by the operating system). Managed code applications can obtain common language runtime services, such as automatic garbage collection, runtime type checking, and security support. These services help provide platform-and language-independent, unified managed-code application behavior.

Managed code is code that can be written in more than 20 high-level languages that support the Microsoft. NET Framework, including: C #, J #, Microsoft Visual Basic. NET, Microsoft JScript. NET, and C + + 。 All languages share a uniform collection of class libraries and can be encoded as intermediate languages (IL). The runtime compiler (Runtime-aware Ompiler) compiles the intermediate language (IL) in the managed execution environment to make it locally executable code, and uses array bounds and index checking, exception handling, garbage collection, and other means to ensure type safety.

Using managed code in a managed execution environment and its compilation avoids many of the typical programming errors that lead to security black holes and unstable programs. Similarly, many unreliable designs are automatically enhanced with security, such as type safety checks, memory management, and the release of invalid objects. Programmers can devote more attention to the application logic design of the program and can reduce the amount of code written. This means shorter development times and more robust programs.

To put it simply, managed code is Microsoft's intermediate language, and his primary role is to compile the source code before the. NET framework's CLR execution code, which means that managed code acts as a translation, and the source code is divided into two phases at run time:

1. Source code compiled into managed code (so the source code can have many kinds, such as vb,c#,j#)

2. Managed code is compiled as a. NET platform-specific file for Microsoft systems (such as class libraries, executables, and so on).

2.1 Unmanaged (unmanaged code)

Code that is executed directly by the operating system outside of the common language runtime environment. Unmanaged code must provide its own garbage collection, type checking, security support, and other services, unlike managed code, which obtains these services from the common language runtime.

Meaning of managed code in. Net

2.2 What is hosting? What does hosting mean?

Managed code, which is based on the. NET metadata format, runs on top of the. NET platform, and all of the exchange with the operating system has. NET to complete, like delegating these functions to. NET, so it's called managed code. Unmanaged code is the reverse.

An example L

Vc.net can also use Mfc,atl to write programs that are based on MFC or ATL rather than. NET, so unmanaged code, if. NET, such as C#,vb.net, is managed code

Unmanaged code refers to the. NET can't explain it.

Simply put, in the case of managed code,. NET can automatically release data, and unmanaged code needs to release the data manually.

What is managed C + +

Hosting is. NET, which advocates a new concept of programming, so we can think of "hosting" as ". NET". C + + Applications that are raised by managed concepts include managed code, managed data, and three components of a managed class.

Managed code

. NET environment provides a number of core runtime services, such as exception handling and security policies. In order to be able to use these services, it is necessary to provide the runtime with some information code (metadata), which is managed code. All C #, vb.net, JScript.NET are managed by default, but Visual C + + is not managed by default, and command-line options (/clr) must be used in the compiler to produce managed code.

Managed data

Managed data is closely related to managed code. Managed data is data that is allocated and freed by a garbage collector that is run by the common language. By default, C #, Visual Basic, and JScript.NET data are managed data. However, by using special keywords, C # data can be marked as unmanaged data. Visual C + + data is unmanaged by default, even when you use the/clr switch.

Managed classes

Although Visual C + + data is unmanaged by default, you can use the "__gc" keyword to mark a class as a managed class when you use Managed Extensions for C + +. As the name suggests, it indicates that the memory of the class instance is managed by the garbage collector. In addition, a managed class can be a member of the. NET framework, and the benefit is that it can interoperate correctly with classes written in other languages, such as managed C + + classes that can inherit from Visual Basic classes. But there are also limitations, such as a managed class can inherit from only one base class.

2.3 How managed code calls unmanaged code (c sharp how to call C + + code)?

Two common practices:

Download:

Http://download.microsoft.com/download/f/2/7/f279e71e-efb0-4155-873d-5554a0608523/CLRInsideOut2007_01.exe

1. COM Interop

Specific operation:

A. Writing a COM service program with ATL

B. Using TlbImp to convert an atl-written COM program into a COM DLL

Use the following command:

TlbImp, you wrote the Com.dll.

TLBIMP is the type library importer that is included with the. NET Framework SDK. Using this command is a managed wrapper that generates an unmanaged COM DLL.

C. Managed client is very simple

Just new, then call the corresponding method.

2. P/invoke

A. Add a DllImport statement to the managed client and a call to a method.

Introducing a P/invoke website, http://pinvoke.net/

This site is primarily a wiki that allows developers to discover, edit, add PInvoke signatures, user-defined types and access to Win32 and other unmanaged APIs from managed code (referred to as C # and VB.net development languages).

Around the world. NET developers can easily share their valuable things to the community,

2.4 Comparison of the efficiency of managed and unmanaged code

Participate in the original text from http://www.cnblogs.com/loverswordsman/articles/1367131.html

More detailed information on http://www.cnblogs.com/loverswordsman/articles/1367131.html

3 Fields of DllImportAttribute

The DllImportAttribute type plays an important role when making p/invoke calls to managed code. The primary role of DllImportAttribute is to give the CLR an indication of which DLL exports the function you want to invoke. The name of the associated DLL is passed as a constructor parameter to DllImportAttribute.

The following table lists all the attribute fields that are related to platform invoke. For each field, the following table will contain its default values, and a link is provided to get information about how to use these fields to define the unmanaged DLL functions. Http://msdn.microsoft.com/zh-cn/library/w4byd5y4.aspx

Field

Description

Bestfitmapping

Enables or disables best bet mapping.

CallingConvention

Specifies the calling convention used to pass method parameters. The default value is WinAPI, which corresponds to the __stdcall of a 32-bit Intel-based platform.

CharSet

Controls the way name reorganization and marshaling string parameters into a function. The default value is CharSet.Ansi.

EntryPoint

Specifies the DLL entry point to invoke.

ExactSpelling

Controls whether entry points should be modified to correspond to character sets. The default values will vary for different programming languages.

PreserveSig

Controls whether the managed method signature should be converted to a return HRESULT and the return value has an unmanaged signature of an additional [out, retval] parameter.

The default value is True (the signature should not be converted).

SetLastError

Allows callers to use the Marshal.GetLastWin32Error API function to determine whether an error occurred while executing the method. In Visual Basic, the default value is true; in C # and C + +, the default value is False.

Throwonunmappablechar

Control throws an exception, converting an unmapped Unicode character to an ANSI "?" Character.

In addition to pointing out the host DLL, DllImportAttribute contains optional properties, four of which are particularly interesting: entrypoint, CharSet, SetLastError, and CallingConvention. Http://www.360doc.com/content/11/0105/09/3877783_84071078.shtml

3.1 entrypoint

The entry point is used to identify the position of the function in the DLL. In a managed object, the original or ordinal entry point of the target function identifies the function that spans the boundary of the interaction operation. In addition, you can map the entry point to a different name, which is actually renaming the function.

The possible reasons for renaming DLL functions are listed below:

· Avoid the use of case-sensitive API function names

· Conforms to the current naming standard

· Provides functions with different data types (by declaring multiple versions of the same DLL function)

· Simplifies the use of APIs that contain ANSI and Unicode versions

You can use the DllImportAttribute.EntryPoint field to specify DLL functions by name or by ordinal. If the name of the function in the method definition is the same as the name of the entry point in the DLL, you do not have to explicitly identify the function with the EntryPoint field. Otherwise, use one of the following attribute forms to indicate the name or ordinal:

l [DllImport ("Dllname", entrypoint= "functionname")]

l [DllImport ("Dllname", entrypoint= "#123")]

When specifying an entry point name, you can provide a string to indicate the name of the DLL that contains the entry point, or you can identify the entry point by ordinal. The number is prefixed with a # symbol, such as #1. If this field is omitted, the common language runtime uses the name of the. NET method marked with DllImportAttribute.

The following example shows how to use the EntryPoint field to replace MessageBoxA in code with MsgBox

Using System.Runtime.InteropServices;

public class Win32 {

[DllImport ("User32.dll", entrypoint= "MessageBoxA")]

public static extern int MsgBox (int hWnd, string text, string caption, uint type);

}

3.2 CharSet

The following are from http://msdn.microsoft.com/zh-cn/library/7b93s42f (v=vs.80). aspx

The DllImportAttribute.CharSet field controls string marshaling and determines how the platform invoke looks for the function name in the DLL. Both of these behaviors are described in this topic.

For functions that take a string argument, some APIs export two versions of them: Narrow (ANSI) and wide (Unicode). For example, the Win32 API contains the following entry point names for the MessageBox function:

· MessageBoxA

Provides a single-byte character ANSI format, characterized by appending a "a" after the entry point name. Calls to MessageBoxA always marshal strings in ANSI format, which is common in Windows 95 and Windows 98 platforms.

· MessageBoxW

Provides a double-byte character Unicode format, characterized by appending a "W" to the entry point name. Calls to MessageBoxW always marshal strings in Unicode format, which is common in Windows NT, Windows 2000, and the Windows XP platform.

The CharSet field accepts the following values:

charset.ansi(default value)

· string marshaling

Platform invoke marshals a string from managed format (Unicode) to ANSI format.

· Name Matching

When the DllImportAttribute.ExactSpelling field is true(it is the default value in Visual Basic 2005), platform invoke will only search for the name that you specify. For example, if you specify a MessageBox, platform invoke will search the MessageBoxand fail if it cannot find the exact same spelling.

When the exactspelling field is false(it is the default value in C + + and C #), platform invoke will first search for an unhandled alias (MessageBox), if an unhandled alias cannot be found. The processed name (messageboxa) is searched. Note that the ANSI name-matching behavior differs from the Unicode name-matching behavior.

CharSet.Unicode

· string marshaling

Platform invoke copies the string from managed format (Unicode) to Unicode format.

· Name Matching

When the exactspelling field is true(it is the default value in Visual Basic 2005), platform invoke will only search for the name that you specify. For example, if you specify a MessageBox, platform invoke will search the MessageBoxand fail if it cannot find the exact same spelling.

When the exactspelling field is false(it is the default value in C + + and C #), platform invoke will first search for the processed name (MessageBoxW) If the processed name cannot be found , the unhandled alias (MessageBox) is searched. Note that the Unicode name-matching behavior differs from the ANSI name-matching behavior.

CharSet.Auto

· Platform invoke selects between ANSI and Unicode formats at run time based on the target platform.

The following example shows the three managed definitions for a MessageBox function that specifies a character set. In the first definition, by omitting, the CharSet character defaults is considered an ANSI character set.

[DllImport ("User32.dll")]

public static extern int MessageBoxA (int hWnd, string text, string caption, uint type);

[DllImport ("User32.dll", CharSet=CharSet.Unicode)]

public static extern int MessageBoxW (int hWnd, string text, string caption, uint type);

[DllImport ("User32.dll", CharSet=CharSet.Auto)]

public static extern int MessageBox (int hWnd, string text, string caption, uint type);

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.

If the DLL function does not handle the text in any way, you can omit the DllImportAttribute CharSet property. However, when Char or String data is part of an equation, you should set the CharSet property to CharSet.Auto. This allows the CLR to use the appropriate character set based on the host OS. If the CharSet property is not explicitly set, its default value is CharSet.Ansi. This default value is flawed because it negatively affects the performance of text parameter marshaling for interop calls made on Windows 2000, Windows XP, and Windows NT®.

The only case where you should explicitly select the CharSet value of CharSet.Ansi or CharSet.Unicode instead of using CharSet.Auto is that you explicitly specify an export function that is specific to one of these two Win32 OS. An example of this is the READDIRECTORYCHANGESW API function, which exists only in Windows NT-based operating systems and only supports Unicode, in which case you should explicitly use CharSet.Unicode.

Sometimes, it is not obvious whether the Windows API has a character set relationship. A confirmation method that is never wrong is to check the C language header file of the function in the Platform SDK. (If you are not sure which header file to look at, you can view the header file for each of the API functions listed in the Platform SDK documentation.) If you find that the API function is indeed defined as a macro that maps to a function name that ends in a or W, the character set is related to the function you are trying to invoke. An example of Windows API functions is the GetMessage API declared in WinUser.h, and you might be surprised to find that it has a and W two versions.

3.3 SetLastError

SetLastError error handling is important, but is often forgotten during programming. When you make P/invoke calls, you also face other challenges-handling the differences between Windows API error handling and exceptions in managed code. I can give you a little advice.

If you are using P/invoke to invoke Windows API functions, and for that function, you use GetLastError to find the extended error message, you should set the SetLastError property to T in the DllImportAttribute of the external method Rue This applies to most external methods.

This causes the CLR to cache the errors set by the API function after each call to the external method. Then, in the wrapper method, you can get the cached error value by calling the Marshal.GetLastWin32Error method defined in the class library's System.Runtime.InteropServices.Marshal type. My advice is to examine these expected error values from the API functions and raise a perceptible exception for those values. For all other failure scenarios (including failure scenarios that are not expected at all), the win32exception defined in the System.ComponentModel namespace is raised and the value returned by Marshal.GetLastWin32Error is passed to it.

3.4 callingconvention

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.

The default value for the CallingConvention field is Winapi, which in turn defaults to the StdCall convention.

Probably the least important one DllImportAttribute property is CallingConvention. This property allows the CLR to indicate which function calling convention should be used for parameters in the stack. The default value of Callingconvention.winapi is the best choice, and it works in most cases. However, if the call does not work, you can examine the declaration header file in the Platform SDK to see if the API function you are calling is an exception API that does not conform to the calling convention standard.

Typically, a calling convention for native functions, such as Windows API functions or C-run-time DLL functions, describes how to push parameters into the thread stack or purge from the thread stack. Most Windows API functions first push the last parameter of a function onto the stack, which is then the responsibility of the called function to clean up the stack. Conversely, many C-run-time DLL functions are defined to push the stack cleanup to the caller in the order in which the method parameters appear in the method signature.

Fortunately, for P/invoke to invoke the job, only the peripheral device understands the calling convention. In general, starting from the default value of Callingconvention.winapi is the best choice. Then, in C run-time DLL functions and a few functions, you may need to change the convention to CALLINGCONVENTION.CDECL.

3.5 exactspelling

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.

3.6 PreserveSig

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.

4 parameter types

L numerical type directly with the corresponding can be. (DWORD, int, WORD, Int16)

The string pointer type-. NET in the API

L. NET in handle (DWord) in API IntPtr

L structure or class in. NET in the API. Note that in this case, you must first qualify the declaration structure or class with the StructLayout attribute

5 several commonly used DLLs in the Win32 API

Dll

Content Description

GDI32.dll

Graphics Device Interface (GDI) functions for device output, such as functions for drawing and font management.

Kernel32.dll

Low-level operating system functions for memory management and resource handling.

User32.dll

Windows management functions for message processing, timers, menus, and communications.

6 DLLs in WinCE

Dll

Content Description

Coredll.dll

Category: Knowledge accumulation

"Reprint" C # DllImport system calls use the introduction of detailed managed code entrypoint

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.