PInvoke .NET ~ C++

本文介绍了PInvoke机制,它能让.NET语言调用DLL中的非托管函数。详细阐述了PInvoke在VB和C#中的使用方法,如VB的两种使用方式、C#使用指针和固定对象的操作等。还提及了参数类型映射,总结了常用Windows数据类型的.NET等效类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.codeproject.com/KB/dotnet/PInvoke.aspx

PInvoke is the mechanism by which .NET languages can call unmanaged functions in DLLs. This is especially useful for calling Windows API functions that aren�t encapsulated by the .NET Framework classes, as well as for other third-party functions provided in DLLs.

PInvoke differs its usage while used in Visual C# or Managed C++ compared with VB because those languages can use pointers or specify unsafe code, which VB cannot.

Using PInvoke in VB

There are mainly two ways in which you can use PInvoke in VB.

  1. Using Declare statement
    minus.gif Collapse
    Declare Auto Function MyMessageBox Lib �user32.dll� Alias _
     �MessageBox� (ByVal hWnd as Integer, ByVal msg as String, _ 
     ByVal Caption as String, ByVal Tpe as Integer) As Integer
    
    Sub Main()
        MyMessageBox(0, "Hello World !!!", "Project  Title", 0)
    End Sub
    
    • Auto/Ansi/Unicode: Character encoding type. Use Auto and leave it up to the compiler to decide.
    • Lib: Library name. Must be in quotes.
    • Name & Alias name for function: If the DLL function name is a VB keyword, then it is needed.
  2. Using DllImport
    minus.gif Collapse
     Imports System.Runtime.InteropServices
     
    <DllImport("User32.dll")> Public Shared Function _ 
      MessageBox(ByVal hWnd As Integer, _ 
      ByVal txt As String, ByVal caption As String, _ 
      ByVal typ As Integer) As Integer
    End Function
    
        Sub Main()
            MessageBox(0, "Imported Hello World !!!", "Project Title", 0)
        End Sub
    

The Declare statement has been provided for backward compatibility with VB 6.0. Actually VB.NET compiler converts Declare to DllImport, but if you need to use any advance options as mentioned below, you have to go for DllImport.

When using DllImport, the function from the DLL is implemented as an empty function with the name, arguments and return type. It has the DllImport attribute, which specifies the name of the DLL containing the function. The runtime will search for it looking in the current directory, the Windows System32 directory, and then in the path. (If name is a keyword then use square braces.)

Following is the list of parameters used with DllImport.

ParameterDescription
BestFitMappingMarshaler will find a best match for chars that can't be mapped between ANSI & Unicode when enabled. Defaults to True.
CallingConventionThe calling convention of a DLL entry point. Defaults to stdcall.
CharSetIndicates how to marshal string data and which entry point to choose when both ANSI and Unicode versions are available. Defaults to Charset.Auto.
EntryPointThis specifies the name or ordinal value of the entry point to be used in the DLL. If not given, function name is used as entry point.
ExactSpellingIt controls whether the interop marshaler will perform name mapping.
PreserveSigSpecifies whether to preserve function signature while conversion.
SetLastErrorWhether the method will call Win32 SetLastError API or not. To retrieve the error, use Marshal.GetLastWin32Error.
ThrowOnUnmappableCharIf false, unmappable characters are replaced by a question mark (?). If true, an exception is thrown when an unmappable character is encountered.

Using PInvoke in C#

Unlike VB, C# does not have the Declare keyword, so we need to use DllImport in C# and Managed C++.

minus.gif Collapse
[DllImport(�user32.dll�]
  public static extern int MessageBoxA(
          int h, string m, string c, int type);

Here the function is declared as static because function is not instance dependent, and extern because C# compiler should be notified not to expect implementation.

C# also provides a way to work with pointers. C# code that uses pointers is called unsafe code and requires the use of keywords: unsafe and fixed. If unsafe flag is not used, it will result in compiler error.

Any operation in C# that involves pointers must take place in an unsafe context. We can use the unsafe keyword at class, method and block levels as shown below.

minus.gif Collapse
public unsafe class myUnsafeClass
{
      //This class can freely use unsafe code.

}
minus.gif Collapse
public class myUnsafeClass
{
      //This class can NOT use unsafe code.

     public unsafe void myUnsafeMethod
     {
            // this method can use unsafe code 

      }
}
minus.gif Collapse
public class myUnsafeClass
{
      //This class can NOT use unsafe code.

     public void myUnsafeMethod
     {
            // this method too can NOT use unsafe code 

            unsafe 
            {
                 // Only this block can use unsafe code.

            }
      }
}
  • stackalloc

    The stackalloc keyword is sometimes used within unsafe blocks to allow allocating a block of memory on the stack rather than on the heap.

  • fixed & pinning

    GC moves objects in managed heap when it compacts memory during a collection.

    If we need to pass a pointer to a managed object to an unmanaged function, we need to ensure that the GC doesn�t move the object while its address is being used through the pointer. This process of fixing an object in memory is called pinning, and it�s accomplished in C# using the fixed keyword.

  • MarshalAs

    MarshalAs attribute can be used to specify how data should be marshaled between managed and unmanaged code when we need to override the defaults. When we are passing a string to a COM method, the default conversion is a COM BSTR; when we are passing a string to a non-COM method, the default conversion is C- LPSTR. But if you want to pass a C-style null-terminated string to a COM method, you will need to use MarshalAs to override the default conversion.

    So far we have seen simple data types. But some of the functions need structures to be passed, which we have to handle differently from simple data types.

  • StructLayout

    We can define a managed type that is the equivalent of an unmanaged structure. The problem with marshaling such types is that the common language runtime controls the layout of managed classes and structures in memory. The StructLayout Attribute allows a developer to control the layout of managed types. Possible values for the StructLayout are Auto, Explicit and Sequential. Charset, Pack and Size are the optional parameters which can be used with the StructLayout attribute.

Callback functions and passing arrays as parameters involve some more complications and can be the subject for the next article.

Parameter type mapping

One of the severe problems with using Platform Invoke is deciding which .NET type to use when declaring the API function. The following table will summarize the .NET equivalents of the most commonly used Windows data types.

Windows Data Type.NET Data Type
BOOL, BOOLEANBoolean or Int32
BSTRString
BYTEByte
CHARChar
DOUBLEDouble
DWORDInt32 or UInt32
FLOATSingle
HANDLE (and all other handle types, such as HFONT and HMENU)IntPtr, UintPtr or HandleRef
HRESULTInt32 or UInt32
INTInt32
LANGIDInt16 or UInt16
LCIDInt32 or UInt32
LONGInt32
LPARAMIntPtr, UintPtr or Object
LPCSTRString
LPCTSTRString
LPCWSTRString
LPSTRString or StringBuilder*
LPTSTRString or StringBuilder
LPWSTRString or StringBuilder
LPVOIDIntPtr, UintPtr or Object
LRESULTIntPtr
SAFEARRAY.NET array type
SHORTInt16
TCHARChar
UCHARSByte
UINTInt32 or UInt32
ULONGInt32 or UInt32
VARIANTObject
VARIANT_BOOLBoolean
WCHARChar
WORDInt16 or UInt16
WPARAMIntPtr, UintPtr or Object

*As the string is an immutable class in .NET, they aren't suitable for use as output parameters. So a StringBuilder is used instead.

转载于:https://www.cnblogs.com/datasci/archive/2010/02/26/1674241.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值