Summary of DllImport attribute, dllimportattribute

Source: Internet
Author: User

Summary of DllImport attribute, dllimportattribute

C # Is there a way to directly use existing functions (for example, some functions in Windows and some methods already written in C ++) without re-coding?

The answer is yes, that is, through the following DllImport.

Namespace of DllImport: using System. Runtime. InteropServices;

Explanation of DllImportAttribute in MSDN: This attribute can be applied to methods.

The DllImportAttribute attribute provides the information necessary to call a function exported from an unmanaged DLL. The name of the DLL containing the entry point must be provided.

The DllImport attribute is defined as follows:

namespace System.Runtime.InteropServices    {     [AttributeUsage(AttributeTargets.Method)]     public class DllImportAttribute: System.Attribute     {      public DllImportAttribute(string dllName) {...}      public CallingConvention CallingConvention;      public CharSet CharSet;      public string EntryPoint;      public bool ExactSpelling;      public bool PreserveSig;      public bool SetLastError;      public string Value { get {...} }     }    }    

Note:
1. DllImport can only be placed on method declaration.
2. DllImport has a single positioning parameter: Specify the dllName parameter that contains the dll name of the imported method.
3. DllImport has five naming parameters:
A. CallingConvention parameter: indicates the call convention of the entry point. If no CallingConvention is specified, use the default value CallingConvention. Winapi.
B. CharSet parameter: indicates the character set used in the entry point. If CharSet is not specified, the default value CharSet. Auto is used.
C. EntryPoint parameter: name of the entry point in the dll. If EntryPoint is not specified, the method name is used.
D. ExactSpelling parameter: indicates whether the EntryPoint must exactly match the spelling of the indicated entry point. If ExactSpelling is not specified, use the default value false.
E. PreserveSig parameter: indicates whether the method signature should be retained or converted. When the signature is converted, it is converted to a signature with an additional output parameter named retval that has the HRESULT return value and the return value. If PreserveSig is not specified, the default value true is used.
F, SetLastError parameter: indicates whether the method retains Win32 "previous error ". If SetLastError is not specified, the default value false is used.
4. It is a one-time attribute class.
5. The method modified with the DllImport attribute must have an extern modifier.

Usage of DllImport:

  DllImport("MyDllImport.dll")]   private static extern int mySum(int a,int b);


1. Use the Win32 class library in C # Programming
Common corresponding types:
1. DWORD is a 4-byte integer, so we can use int or uint as the corresponding type of C.
2. the bool type corresponds to the BOOL type.

Example 1: Call Beep () API to make sound
Beep () is defined in kernel32.lib and defined in MSDN. Beep has the following prototype:

BOOL Beep (DWORD dwFreq, // sound frequency DWORD dwDuration // sound duration );

Use C # To compile the following prototype:

[DllImport("kernel32.dll")] public static extern bool Beep(int frequency, int duration);


Example 2: Enumeration type and constant
MessageBeep () is defined in user32.lib. In MSDN, MessageBeep has the following prototype:

BOOL MessageBeep (UINT uType // sound type );

Use C # To compile the prototype:

public enum BeepType{  SimpleBeep = -1,  IconAsterisk = 0x00000040,  IconExclamation = 0x00000030,  IconHand = 0x00000010,  IconQuestion = 0x00000020,  Ok = 0x00000000,} 

The uType parameter actually accepts a set of predefined constants. It is reasonable to use the enum type for the uType parameter.

[DllImport("user32.dll")]public static extern bool MessageBeep(BeepType beepType);  


Example 3: Processing Structure
Determine the battery status of the notebook if necessary. Win32 provides a power management function. You can find the GetSystemPowerStatus () function by searching for MSDN.

  BOOL GetSystemPowerStatus(                               LPSYSTEM_POWER_STATUS lpSystemPowerStatus                              );

This function contains a pointer to a structure that we have not processed. To process the structure, we need to use C # to define the structure. We start with the definition of unmanaged systems:

typedef struct _SYSTEM_POWER_STATUS {    BYTE  ACLineStatus;    BYTE  BatteryFlag;    BYTE  BatteryLifePercent;    BYTE  Reserved1;    DWORD BatteryLifeTime;    DWORD BatteryFullLifeTime; } SYSTEM_POWER_STATUS, *LPSYSTEM_POWER_STATUS; 

Then, use the C # type instead of the C type to get the C # version.

struct SystemPowerStatus {   byte ACLineStatus;   byte batteryFlag;   byte batteryLifePercent;   byte reserved1;   int batteryLifeTime;   int batteryFullLifeTime; } 

In this way, you can easily compile the C # prototype:

[DllImport("kernel32.dll")] public static extern bool GetSystemPowerStatus( ref SystemPowerStatus systemPowerStatus); 

In this prototype, we use "ref" to specify that the structure pointer will be passed instead of the structure value. This is a general method for processing the structure passed through pointers.
This function works well, but it is best to define the ACLineStatus and batteryFlag fields as enum:

    enum ACLineStatus: byte    {     Offline = 0,     Online = 1,     Unknown = 255,    }    enum BatteryFlag: byte    {     High = 1,     Low = 2,     Critical = 4,     Charging = 8,     NoSystemBattery = 128,     Unknown = 255,    } 

Note that because the fields in the structure are some bytes, we use byte as the basic type of The enum.

Example 4: Processing string


Call C ++ code in C #
Int type

[DllImport ("MyDLL. dll ")] // return int type public static extern int mySum (int a1, int b1); // declare extern" C "_ declspec (dllexport) in DLL) int WINAPI mySum (int a2, int b2) {// a2 b2 cannot change a1 b1 // a2 = .. // b2 =... return a + B;} // pass the int type public static extern int mySum (ref int a1, ref int b1 ); // declare extern "C" _ declspec (dllexport) int WINAPI mySum (int * a2, int * b2) in DLL {// a1 can be changed, b1 * a2 =... * b2 =... return a + B ;}

The DLL must be of the char * type.

[DllImport ("MyDLL. dll ")] // input value public static extern int mySum (string astr1, string bstr1); // declare extern" C "_ declspec (dllexport) in DLL) int WINAPI mySum (char * astr2, char * bstr2) {// change astr2 bstr 2, astr1 bstr1 will not be changed return a + B ;}


DLL needs to output char * type

[DllImport ("MyDLL. dll ")] // output value public static extern int mySum (StringBuilder abuf, StringBuilder bbuf); // declare extern" C "_ declspec (dllexport) in DLL) int WINAPI mySum (char * astr, char * bstr) {// output char * changes astr bstr --> abuf, bbuf can be changed to return a + B ;}

DLL callback function

BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam) 
Using System; using System. runtime. interopServices; public delegate bool CallBack (int hwnd, int lParam); // defines the delegate function type 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 ;}}

DLL Transfer Structure

BOOL PtInRect(const RECT *lprc, POINT pt); 
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 XXXX { [DllImport("User32.dll")] public static extern bool PtInRect(ref Rect r, Point p); }

 



Related Article

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.