当前位置:首页 > Windows程序 > 正文

使用C#调用windows API(从其它地方总结来的,以备查询)

2021-03-25 Windows程序

标签:

使用C#调用windows API(从其它地方总结来的,以备查询)

C#调用windows API也可以叫做C#如何直接调用非托管代码,通常有2种方法:

1.  直接调用从 DLL 导出的函数。

2.  调用 COM 对象上的接口方法

我主要讨论从dll中导出函数,基本步骤如下:

1.使用 C# 关键字 static 和 extern 声明方法。

2.将 DllImport 属性附加到该方法。DllImport 属性允许您指定包含该方法的 DLL 的名称。

3.如果需要,为方法的参数和返回值指定自定义封送处理信息,这将重写 .NET Framework 的默认封送处理。

1.首先我们查询MSDN找到GetShortPathName的原型定义

DWORD GetShortPathName(

LPCTSTR lpszLongPath,

LPTSTR lpszShortPath,

DWORD cchBuffer

);

2.查找对照表进行数据类型的转换(出处:?fig=true  Data

Win32 Types

 

Specification

 

CLR Type

 

char, INT8, SBYTE, CHAR†

 

8-bit signed integer

 

System.SByte

 

short, short int, INT16, SHORT

 

16-bit signed integer

 

System.Int16

 

int, long, long int, INT32, LONG32, BOOL†, INT

 

32-bit signed integer

 

System.Int32

 

__int64, INT64, LONGLONG

 

64-bit signed integer

 

System.Int64

 

unsigned char, UINT8, UCHAR†, BYTE

 

8-bit unsigned integer

 

System.Byte

 

unsigned short, UINT16, USHORT, WORD, ATOM, WCHAR†, __wchar_t

 

16-bit unsigned integer

 

System.UInt16

 

unsigned, unsigned int, UINT32, ULONG32, DWORD32, ULONG, DWORD, UINT

 

32-bit unsigned integer

 

System.UInt32

 

unsigned __int64, UINT64, DWORDLONG, ULONGLONG

 

64-bit unsigned integer

 

System.UInt64

 

float, FLOAT

 

Single-precision floating point

 

System.Single

 

double, long double, DOUBLE

 

Double-precision floating point

 

System.Double

 

†In Win32 this type is an integer with a specially assigned meaning; in contrast, the CLR provides a specific type devoted to this meaning.

 

3.调用GetShortPathName这个API,简单的写法如下(编译通过的话),

using System;

using System.Runtime.InteropServices;

public class MSSQL_ServerHandler

{

[DllImport("kernel32.dll")]

public static extern int GetShortPathName

(

string path,

StringBuilder shortPath,

int shortPathLength

)

}

而我们之前的例子:

using System;

using System.Runtime.InteropServices;

public class MSSQL_ServerHandler

{

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]

public static extern int GetShortPathName

(

[MarshalAs(UnmanagedType.LPTStr)] string path,

[MarshalAs(UnmanagedType.LPTStr)] StringBuilder shortPath,

int shortPathLength

)

}

对比可知,其中DllImport ,static,extern基本上是必须有的,其他CharSet,MarshalAs(…)是可选项,在这里即使没有,程序也是可以调用此API了。

说明:

1.MSSQL_ServerHandler. GetShortPathName 方法用 static 和 extern 修饰符声明并且具有 DllImport 属性,该属性使用默认名称GetShortPathName 通知编译器此实现来自kernel32.dll。若要对 C# 方法使用不同的名称(如 getShort),则必须在 DllImport 属性中使用 EntryPoint 选项,如下所示:

[DllImport("kernel32.dll", EntryPoint="getShort")]

2使用MarshalAs(UnmanagedType.LPTStr)保证了在任何平台上都会得到LPTStr,否则默认的方式会把从C#中的字符串作为BStr传递。

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/67117.html