Technology Sharing

global::System.Runtime.InteropServices.DllImport

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

In C# programming,[global::System.Runtime.InteropServices.DllImport]Is an attribute that is used to mark the entry point of an unmanaged code (usually a DLL or library written in C or C++) so that C# code can call it. This feature is part of the P/Invoke (Platform Invocation Services) mechanism, which allows C# code to interact with code in other programming languages.

When you see this feature, it is usually used to import a function in a DLL so that it can be called from C# code. For example:

  1. using System;
  2. using System.Runtime.InteropServices;
  3. class NativeMethods
  4. {
  5. // 导入DLL中的函数
  6. [DllImport("MyNativeLibrary.dll")]
  7. public static extern int MyNativeMethod(int a, int b);
  8. }
  9. class Program
  10. {
  11. static void Main()
  12. {
  13. // 调用DLL中的函数
  14. int result = NativeMethods.MyNativeMethod(1, 2);
  15. Console.WriteLine(result);
  16. }
  17. }

In this example,MyNativeMethodis aMyNativeLibrary.dll, which is imported into C# code so that it can be used inMainMethod called.

DllImportThe attribute has several parameters, but the most common one is the name of the DLL (as in the example above). Other parameters may include the calling convention (CallingConvention), CharSet (the character set used for strings), etc.

Note: When using P/Invoke with a DLL, you must ensure that the DLL is compatible with your application (that is, they use the same runtime environment and the DLL is compiled for your operating system and architecture). In addition, because P/Invoke bypasses C#'s type safety system, you must take extra care to ensure that the parameters passed and the values ​​returned exactly match the function signatures in the DLL.