Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
DllImport Attribute is a declarative tag used in C# to mark a class method as being defined in an external dynamic-link library (DLL) rather than in any .NET assembly.
DllImport attribute is used at run time to call a function exported in an external DLL implemented with unmanaged code that is executed outside the control of common language runtime (CLR). It is also used to specify other information needed while calling the function such as calling convention, type of conversion of parameters passed between managed and unmanaged code, etc. Thus, it is used to interoperate with code in unmanaged and legacy components that reside in Windows DLLs and is written in C or C++.
DllImport is helpful in situations where the functionality of a managed application, whose code is executed by CLR, can be extended only by accessing and reusing the functionality of the Win32 application programming interface (API) and other user-defined, unmanaged codes that are implemented in DLL. This can save development effort and make use of existing robust and well-tested code without reinventing the wheel in a managed application. It is usually needed while using DLLs that cannot be rewritten but have the ability to be modified.
The DllImport attribute is a declaration statement for the exported function to be called from the managed application. It cannot be used for a member function, which requires an instance of class. It is specified at design time within square braces before the declaration of the method for which it is applied. It is necessary to use the string “extern” before the function declaration.
For instance, the DllImport attribute can be used in the Windows Forms application, which is a managed application to invoke a method of a component object model component (whose code is unmanaged) for performing some calculations.
It is designed to import the traditional DLLs that export their functions using the original Windows DLL export mechanism. It is not intended for using code in managed assembly (as DLL), which can be referenced directly in the managed application's project.
DllImport attribute uses the InteropServices of the CLR, which executes the call from managed code to unmanaged code. It also informs the compiler about the location of the implementation of the function used. When the unmanaged wrapper function with this attribute in managed code is called, the CLR locates and loads the necessary DLL. It marshals (converts the parameters as per the specification) and returns back the unmanaged code after execution, along with proper conversion of parameters.
While using DllImport attribute, care needs to be taken to use the correct name of the DLL and the exported function because typos may occur in places where they cannot be easily detected.