DllImport in. Net

Source: Internet
Author: User
Tags win32

Only C + + DLLs that are made into COM can be referenced directly. You can only use P/invoke (DllImport) or C + +/CLI without COM. But P/invoke easy type is not on, so if the function is more, preferably with C + +/CLI.

---------------------------------------------

C + + DLLs are divided into two types, the article is described incorrectly.
As described in the article is a static DLL, a dynamic DLL can be directly referenced

-------------------------------------------------

VC + + main string types are: Lpstr,lpcstr, LPCTSTR, String, CString, LPCWSTR, LPWSTR and so on but the C # type is not exactly the same, only the data type corresponds correctly to obtain the correct data.

Type comparison:

BSTR---------StringBuilder

LPCTSTR---------StringBuilder

LPCWSTR---------IntPtr

Handle---------INTPTR

HWND-----------INTPTR

char *----------string

int *-----------ref int

int &-----------Ref int

void *----------INTPTR

unsigned char *-----ref BYTE

5. Transfer of structural parameters

For structural parameters, we need to construct the corresponding structure in C #, and use the Marshal class to convert the struct to the pointer address to C + + function, obtain the data and then obtain the corresponding structure according to the pointer address.

HREE Structthree = new Three ();             IntPtr Ptrthree = Marshal.allochglobal (marshal.sizeof (Structthree));             Marshal.structuretoptr (Structthree, Ptrthree, false);             _enc7481_get_threeencoder2 (Ptrthree); Structthree = (three) marshal.ptrtostructure (Ptrthree, typeof (three));

--------------------------------------------------

DllImport The name space using System.Runtime.InteropServices;

The explanation for DllImportAttribute in MSDN is this: You can apply this property to a method. The DllImportAttribute property provides the information necessary to invoke a function that is exported from an unmanaged DLL.

As a minimum requirement, you must provide the name of the DLL that contains the entry point

The DllImport property 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 {...}}

}

}

Description

1, DllImport can only be placed on the method declaration.

2. DllImport has a single positional parameter: Specifies the DllName parameter that contains the DLL name of the imported method.

3. DllImport has five named parameters:

A, the CallingConvention parameter indicates the calling convention of the entry point. If CallingConvention is not specified, the default value of Callingconvention.winapi is used.

b, the CharSet parameter indicates the character set used in the entry point. If CharSet is not specified, the default value of CharSet.Auto is used.

The C,entrypoint parameter gives the name of the entry point in the DLL.    If entrypoint is not specified, the name of the method itself is used.

The D, exactspelling parameter indicates whether the entrypoint must exactly match the spelling of the indicated entry point. If ExactSpelling is not specified, the default value of false is used.

E, the PreserveSig parameter indicates whether the signature of the method should be preserved or converted. When the signature is converted, it is converted to a signature of an additional output parameter named RetVal with the HRESULT return value and the return value. If PreserveSig is not specified, the default value of True is used.

The F, setlasterror parameter indicates whether the method retains Win32 "previous error". If SetLastError is not specified, the default value of false is used.

4, it is a one-time attribute class.

5. In addition, methods decorated with the DllImport attribute must have an extern modifier.

Usage of dllimport:

DllImport ("MyDllImport.dll")] private static extern int mySum (int a,int b); The use of the Win32 class library in C # programming

Common Types of correspondence:

1, a DWORD is a 4-byte integer, so we can use an int or uint as the C # corresponding type.

2, bool type and bool corresponding.

Example one: Call the Beep () API to make a sound

Beep () is defined in Kernel32.lib, defined in MSDN, Beep has the following prototypes:

BOOL Beep (DWORD dwfreq,//Sound frequency

DWORD dwduration//sound duration);

Write the following prototypes in C #:

[DllImport ("kernel32.dll")]

public static extern bool Beep (int frequency, int duration);

Example two: enumeration types and Constants

MessageBeep () is defined in User32.lib, defined in MSDN, MessageBeep has the following prototypes:

BOOL MessageBeep (UINT utype//sound type

);

Write the prototype in C #:

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, and it is reasonable to use the enum type for the Utype parameter.

[DllImport ("User32.dll")]

public static extern bool MessageBeep (Beeptype beeptype);

Example three: processing structure

Sometimes I need to determine the battery condition of my laptop. WIN32 provides power management functions for this purpose, and searching MSDN can find the GetSystemPowerStatus () function.

BOOL GetSystemPowerStatus (

Lpsystem_power_status Lpsystempowerstatus

);

This function contains a pointer to a struct that we have not processed. To work with structs, we need to define the structure in C #. We start with an unmanaged definition:

typedef struct _SYSTEM_POWER_STATUS {

BYTE ACLineStatus;

BYTE Batteryflag;

BYTE batterylifepercent;

BYTE Reserved1;

DWORD Batterylifetime;

DWORD BatteryFullLifetime;

} system_power_status, *lpsystem_power_status;

Then, you get the C # version by replacing C type with a C # type.

struct SystemPowerStatus

{

BYTE ACLineStatus;

BYTE Batteryflag;

BYTE BatteryLifePercent;

BYTE reserved1;

int batterylifetime;

int batteryfulllifetime;

}

This makes it easy to write a C # prototype:

[DllImport ("kernel32.dll")]

public static extern bool GetSystemPowerStatus (

Ref SystemPowerStatus SystemPowerStatus);

In this prototype, we use "ref" to indicate that the struct pointer will be passed instead of the structure value. This is the general method of handling the structure passed through the pointer.

This function works fine, but it's a good idea to define the ACLineStatus and Batteryflag fields as enums:

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 structure field is some bytes, we use byte as the basic type of the enum

Example four: Working with strings

Calling C + + code in two C #

int type

[DllImport ("MyDLL.dll")]

Returns an int type

public static extern int MySum (int a1,int B1);

DLL in the Declaration

extern "C" __declspec (dllexport) int WINAPI mySum (int a2,int B2)

{

A2 B2 can't change A1 B1

A2=.

B2= ...

return a+b;

}

Parameter passed int type public static extern int MySum (ref int A1,REF int B1); DLL declares extern "C" __declspec (dllexport) int WINAPI mySum (int *a2,int *b2) {//can change A1, B1 *a2= ... *b2= ... return a+b; }
_disibledevent= "0" >

DllImport in. Net

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.