Use vs [DllImport]?

I was wondering what the most popular ads are and why do we still need to use DllImport? I say C #.

+8
c # using pinvoke dllimport
source share
6 answers

From the MDSN documentation :

The DllImport attribute is very useful when reusing existing unmanaged code in a managed application. For example, your managed application might need to make unmanaged WIN32 API calls.

Basically, when you write a .NET application, and the library does not have a managed shell (it is written in unmanaged code), you need to use DllImport to interact with it. Otherwise, you can reference managed libraries using the using statement, as usual, in any library of the base class.

+10
source share

Used when you need to call unmanaged code.

For example, you might need to make a call to the Windows API function so that you can do something like this:

 [DllImport("Advapi32.dll", EntryPoint="GetUserName", ExactSpelling=false, SetLastError=true)] static extern bool GetUserName( [MarshalAs(UnmanagedType.LPArray)] byte[] lpBuffer, [MarshalAs(UnmanagedType.LPArray)] Int32[] nSize ); 

links: http://www.csharphelp.com/2006/01/call-unmanaged-code-part-1-simple-dllimport/

+5
source share

DLLImport is used to import your own dll library into a managed (.net) application. For example, a library written in C ++ can be imported and used in your C # project.

Use is used to refer to a namespace located in one of the managed link libraries. These are usually .net assemblies.

+2
source share

DllImport is designed to import a function that is contained in a DLL that is not managed by .NET. The using statements are designed so that your code can easily reference other .NET assemblies without using a fully qualified name.

+1
source share

Visual Studio creates basic links for you (for example, System).

You do not need DllImport if you do not want to use your own libraries

+1
source share

The using directive includes the namespace from the managed assembly referenced.
DllImport used to import methods from unmanaged DLL files.

+1
source share

All Articles