C USES DllImport to call methods on unmanaged code

  • 2020-05-10 18:38:29
  • OfStack

Find the GetShortPathName method signature,

DWORD GetShortPathName (LPCTSTR tpszLongPath, TPTSTR lpszShortPath, DWORD cchBuffer);

Correspondence between unmanaged and managed data types:

LPCTSTR                 String

LPTSTR                     StringBuilder

DWORD                   int

Import rules for DllImport:

1. The method name is exactly the same as Win API. If a completely different method name is displayed when invoked in C#, you need to introduce the EntryPoint property, which is displayed using an alias.

2. In addition to the class DllImport modifier, the function needs to declare the public static extern type.

3. The return value and parameters of the function must be exactly the same as the API called.

4. The System.Runtime.InteropServices namespace must be introduced.

Code:


using System.Runtime.InteropServices;
public class Test
        {
            [DllImport("kernel32.dll",CharSet=CharSet.Auto,EntryPoint="GetShort")]
public static extern int GetShortPathName(
                [MarshalAs(UnmanagedType.LPTStr)] String path,
                [MarshalAs(UnmanagedType.LPTStr)] StringBuilder shortPath,
int shortPathLength);
        }

The path of kernel32.dll in the code call is not written because DllImport looks for Dll in the following three orders:

1. Directory where exe is located; 2. System32 directory; 3. Directory of environment variables.

MarshalAs is optional because each data type has a default marshaling behavior. This property indicates how to marshal data between managed code and unmanaged code, and can be used for parameters, fields, and return values. Most of the time, this property can be satisfied with most unmanaged data types simply by using the UnmanagedType enumeration type. If the character is passed into Dll as BStr by default, MarshalAs can be used to specify the string as LPTStr, LPWStr, LPStr, etc.

DllImport optional attribute interpretation

EntryPoint                     can use different names for methods, using aliases

CharSet                         function calls use Unicode or Ansi Ansi

ExactSpelling             False, which means let the compiler choose to use Unicode or Ansi

CallingConvetnion                         its parameters indicate the convention of the entry point call; The default is not specified as CallingConvention.WinAPI

PreserveSig                         indicates whether the method signature should be retained or converted, When converted, it is converted to a signature with an HRESULT return value and an additional output parameter named retval for that return value, which defaults to true.

SetLastError                              


Related articles: