共用方式為


Using Explicit PInvoke in C++ (DllImport Attribute)

 

The latest version of this topic can be found at Using Explicit PInvoke in C++ (DllImport Attribute).

The .NET Framework provides explicit Platform Invoke (or PInvoke) features with the Dllimport attribute to allow managed applications to call unmanaged functions packaged inside DLLs. Explicit PInvoke is required for situations where unmanaged APIs are packaged as DLLs and the source code is not available. Calling Win32 functions, for example, requires PInvoke. Otherwise, use implicit P{Invoke; see Using C++ Interop (Implicit PInvoke) for more information.

PInvoke works by using DllImportAttribute. This attribute, which takes the name of the DLL as its first argument, is placed before a function declaration for each DLL entry point that will be used. The signature of the function must match the name of a function exported by the DLL (but some type conversion can be performed implicitly by defining the DllImport declarations in terms of managed types.)

The result is a managed entry point for each native DLL function that contains the necessary transition code (or thunk) and simple data conversions. Managed functions can then call into the DLL through these entry points. The code inserted into a module as the result of PInvoke is entirely managed and explicit PInvoke is supported for /clr, /clr:pure, and /clr:safe compilations. For more information, see Pure and Verifiable Code (C++/CLI).

In This Section

See Also

Calling Native Functions from Managed Code