Find the method signature for getmediapathname,
DWORD getaskpathname (LPCTSTR tpszLongPath, TPTSTR lpsz+path, DWORD cchBuffer );
Relationship between unmanaged and managed data types:
LPCTSTR String
LPTSTR StringBuilder
DWORD int
DllImport import rules:
1. The method name is exactly the same as that of Win API. If different method names are displayed in the C # Call, You need to introduce the EntryPoint attribute and use the alias for display.
2. In addition to the DllImport class modifier, the function also needs to declare the public static extern type.
3. function return values and parameters must be exactly the same as those of the called API.
4. The System. Runtime. InteropServices namespace must be introduced.
Code:
Copy codeThe Code is as follows: using System. Runtime. InteropServices;
Public class Test
{
[DllImport ("kernel32.dll", CharSet = CharSet. Auto, EntryPoint = "GetShort")]
Public static extern int getaskpathname (
[Financialas (UnmanagedType. LPTStr)] String path,
[Financialas (UnmanagedType. LPTStr)] StringBuilder implements path,
Int bytes pathlength );
}
In the Code call, the kernel32.dll path is not written because DllImport searches for the Dll in the following three sequence:
1. exe directory; 2. System32 directory; 3. Environment Variable directory.
Financialas is optional. Because each data type has a default sending behavior, this attribute indicates how to send data between hosted code and unmanaged code, this attribute can be used for parameters, fields, and return values. In most cases, this attribute can only meet the requirements of most unmanaged data types by using the UnmanagedType Enumeration type. For example, by default, the characters will be passed into the Dll as BStr, you can use financialas to specify the string as LPTStr, LPWStr, or LPStr.
Description of optional DllImport attributes
EntryPoint can use different names and aliases for methods.
Use Unicode or Ansi for CharSet function calls
ExactSpelling False indicates that the compiler should choose Unicode or Ansi.
CallingConvetnion: Its Parameter indicates the Convention for calling the entry point; it is not specified as CallingConvention. WinAPI by default
PreserveSig indicates whether the method signature should be retained or converted. When it is converted, it is converted into a signature with an additional output parameter named retval that has the HRESULT returned value and the returned value, the default value is true.
SetLastError indicates whether to retain the previous error. The default value is false.