[DllImport("user32.dll")] and extern usage and examples in C#

       Original: https://blog.csdn.net/micellehsiao/article/details/7629746
        The extern  modifier is used to declare a method implemented externally. A common use of the extern  modifier is with the DllImport attribute when using Interop services to call into unmanaged code. In this case, the method must also be declared static ,as shown in the following example:
[DllImport("user32.dll.dll")]
private static extern void IsWindowVisible();

        The extern keyword can also define external assembly aliases, making it possible to reference different versions of the same component from a single assembly. It is an error to use the abstract and extern modifiers together to modify the same member, using the extern modifier means that the method is implemented outside the C# code, and using the abstract modifier means that the method implementation is not provided in the class. This defines the declarative dynamic link library user32.dll as the static entry point.

        The difference between introducing a DLL through DllImport in a VS project and adding a DLL by adding a reference is: DllImpor is for unmanaged, and unmanaged refers to DLLs generated without .net; references are for managed .

        static extern int IsWindowVisible(); means to declare an external implementation method IsWindowVisible(), which must be present in your own dll. Your IsWindowVisible method must exist in the dll and the dll does not have to be registered. Registration is to let the system know where it is and some information. You specify the location and register an effect. DLLimport supports DLLs that are not under the .net framework, such as those written in C++. DLLs written in the .net framework can be directly referenced.

Application examples:

The example uses a C program to create a DLL that will be called from the C# program in the next example.

// cmdll.c
// Compile with: /LD
int __declspec(dllexport) SampleMethod(int i)
{
   return i*10;
}

The example uses two files  CM.cs  and  Cmdll.c  to illustrate  extern .  The C file is the external DLL created in Example 2, which is called from within the C# program.

// cm.cs
using System;
using System.Runtime.InteropServices;
public class MainClass
{
   [DllImport("Cmdll.dll")]
   public static extern int SampleMethod(int x);

   static void Main()
   {
      Console.WriteLine("SampleMethod() returns {0}.", SampleMethod(5));
   }
}
SampleMethod() returns 50.

Build the project:

  • Compile Cmdll.c  into a DLL using the Visual C++ command line  :

    cl /LD Cmdll.c

  • Compile CM.cs using the command line  :

    csc CM.cs

This will create the executable file  CM.exe .  When this program is run, SampleMethod  passes the value 5 to the DLL file, which multiplies this value by 10 and returns it.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325341140&siteId=291194637