Usage of dllimport

Source: Internet
Author: User

DllimportIs an Attribute Class in the namespace of system. runtime. interopservices. Its function is to provide necessary call information for functions exported from unmanaged DLL.
When the dllimport attribute is applied to a method, the DLL name containing the entry point must be provided at least.
DllimportIs defined as follows:

[Attributeusage (attributetargets. Method)]

Public class dllimportattribute: system. Attribute

{

Public dllimportattribute (string dllname ){...} // The positioning parameter is dllname.

Public callingconvention; // call convention for the entry point

Public charset; // string used by the entry point

Public String entrypoint; // entry point name

Public bool exactspelling; // whether the spelling must be exactly the same as that indicated at the entry point. The default value is false.

Public bool preservesig; // whether the signature of the method is retained or converted

Public bool setlasterror; // the return value of the findlasterror method is stored here

Public String Value {get {...} }

}

Usage example:

[Dllimport ("Kernel32")]

Private Static extern long writeprivateprofilestring (string section, string key, string Val, string filepath );

The above is a WIN32API used to write INI files.

In this way, the Data Type of WIN32API is corresponding to DWORD = int or uint, bool = bool, predefined constant = Enum, and structure = struct.
 

Dllimport will automatically go to the desired location in order: 1. EXE directory 2, system32 directory 3, environment variable directory so you only need to copy the referenced DLL to these three directories, you do not need to write the path, or you can use this server. mappath (. \ bin \*. DLL) in the Web, and later found in the application using [dllimport (@ "C: \ OJ \ bin \ judge. DLL ")] so that the absolute path of the specified dll can be loaded normally. This problem occurs most often when a third-party Unmanaged DLL component is used. net team's official solution is as follows: first, you need to confirm which components you reference, which are hosted and which are not hosted. it is easy to host and directly referenced by the user. for indirect use, you need to copy it to the bin directory. non-hosted processing will be troublesome. in fact, copying to the bin does not help, because the CLR will copy the file to a temporary directory and then run the Web, while the CLR will only copy the hosted file, this is why we obviously put the unmanaged DLL under the bin but still prompt that the module cannot be loaded. the specific method is as follows: first, create a directory on the server, for example, C: \ DLL. Then, add the directory to the PATH variable in the environment variable, copy all the unmanaged files to c: \ DLL. or simply put the DLL in the System32 directory. For applications that can be deployed by ourselves, this is not a solution. However, if we use a virtual space, we cannot Register the PATH variable or copy our own DLL to the System32 directory. At the same time, we do not necessarily know the physical path of our DLL. Dllimport can only use string constants, but cannot use server. mappath (@"~ /Bin/judge. dll ") to determine the physical path. ASP. to use dllimport in. net, you must first "using system. runtime. interopservices; "However, I found that calling this" Unmanaged DLL "is quite slow, probably because my method requires remote verification, but it is too slow. After a thorough research, we finally come up with a perfect solution. First, we use

[Dllimport ("kernel32.dll")]

Private extern static intptr loadlibrary (string path );

[Dllimport ("kernel32.dll")]

Private extern static intptr getprocaddress (intptr Lib, string funcname );

[Dllimport ("kernel32.dll")]

Private extern static bool freelibrary (intptr Lib );

Obtain the addresses of the loadlibrary and getprocaddress functions respectively, and then use these two functions to obtain the functions in our DLL.
We can use server. mappath (@"~ /Bin/judge. dll ") to obtain the physical path of our DLL, load it with loadlibrary, and finally use getprocaddress to obtain the function address to use.

The following custom class code completes loadlibrary loading and function calling:

Public class dllinvoke

{

[Dllimport ("kernel32.dll")]

Private extern static intptr loadlibrary (string path );

[Dllimport ("kernel32.dll")]

Private extern static intptr getprocaddress (intptr Lib, string funcname );

[Dllimport ("kernel32.dll")]

Private extern static bool freelibrary (intptr Lib );

Private intptr hlib;

Public dllinvoke (string dllpath)

{

Hlib = loadlibrary (dllpath );

}

~ Dllinvoke ()

{

Freelibrary (hlib );

}

// Convert the function to be executed to the Delegate

Public Delegate invoke (string apiname, type T)

{

Intptr API = getprocaddress (hlib, apiname );

Return (delegate) Marshal. getdelegateforfunctionpointer (API, t );

}

}

The following code calls

Public Delegate int compile (string command, stringbuilder inf );

// Compile

Dllinvoke DLL = new dllinvoke (server. mappath (@"~ /Bin/judge. dll "));

Compile compile = (compile) DLL. Invoke ("compile", typeof (compile ));

Stringbuilder INF;

Compile (@ "gcc a. C-o a.exe", INF); // call the compile function defined in my DLL.

When you study C # In actual work, you may ask: why do we need to provide some existing functions (for example, some functions in windows, some methods that have been compiled in C ++) to rewrite the code, can C # directly use these existing functions? The answer is yes. You can directly call these functions through dllimport in C. The namespace using system. runtime. interopservices where dllimport is located. The explanation of dllimportattribute in msdn is as follows: This attribute can be applied to methods. The dllimportattribute attribute provides the information necessary to call a function exported from an unmanaged DLL. As the minimum requirement, 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;

Public 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. The callingconvention parameter indicates the call convention of the entry point. If no callingconvention is specified, use the default value callingconvention. winapi.
B. The charset parameter indicates the character set used in the entry point. If charset is not specified, the default value charset. Auto is used.
C. The entrypoint parameter specifies the name of the DLL entry point. If entrypoint is not specified, the method name is used.
D. The 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. The 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.
The F and setlasterror parameters indicate 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. In addition, the method modified with the dllimport attribute must have an extern modifier.

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.