SysTime 示例
更新:2007 年 11 月
此示例演示如何将一个指向类的指针传递给一个需要指向结构的指针的非托管函数。
SysTime 示例使用以下非托管函数(这里同时显示其原始函数声明):
从 Kernel32.dll 导出的 GetSystemTime。
VOID GetSystemTime(LPSYSTEMTIME lpSystemTime);
传递到该函数的初始结构包含以下元素:
typedef struct _SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME;
在该示例中,SystemTime 类包含表示为类成员的原始结构的元素。StructLayoutAttribute 属性经过设置,可确保成员在内存中按它们的出现顺序依次排列。
LibWrap 类包含 GetSystemTime 方法的托管原型,默认情况下,它将 SystemTime 类作为 In/Out 参数进行传递。必须用 InAttribute 和 OutAttribute 属性声明该参数,因为作为引用类型的类在默认情况下将作为 In 参数进行传递。为使调用方接收结果,必须显式应用这些方向属性。App 类创建 SystemTime 类的一个新实例,然后访问其数据字段。
下面的代码示例的源代码由 .NET Framework 平台调用技术示例 提供。
代码示例
Imports System
Imports System.Runtime.InteropServices ' For StructLayout,
' and DllImport
' Declares a class member for each structure element.
<StructLayout(LayoutKind.Sequential)> _
Public Class SystemTime
Public year As Short
Public month As Short
Public weekday As Short
Public day As Short
Public hour As Short
Public minute As Short
Public second As Short
Public millisecond As Short
End Class 'SystemTime
Public Class LibWrap
' Declares a managed prototype for the unmanaged function.
Declare Sub GetSystemTime Lib "Kernel32.dll" _
(<[In](), Out()> ByVal st As SystemTime)
End Class 'LibWrap
Public Class App
Public Shared Sub Main()
Console.WriteLine("VB .NET SysTime Sample using " _
+ "Platform Invoke")
Dim st As New SystemTime()
LibWrap.GetSystemTime(st)
Console.Write("The Date is: " _
+ "{0} {1} {2}", st.month, st.day, st.year)
End Sub 'Main
End Class 'App
所需的输出:
VB .NET SysTime Sample using Platform Invoke
The Date is: 10 31 2006
using System;
using System.Runtime.InteropServices; // For StructLayout, DllImport
[ StructLayout( LayoutKind.Sequential )]
public class SystemTime
{
public ushort year;
public ushort month;
public ushort weekday;
public ushort day;
public ushort hour;
public ushort minute;
public ushort second;
public ushort millisecond;
}
public class LibWrap
{
// Declares a managed prototype for the unmanaged function using Platform Invoke.
[ DllImport( "Kernel32.dll" )]
public static extern void GetSystemTime( [In,Out] SystemTime st );
}
public class App
{
public static void Main()
{
Console.WriteLine("C# SysTime Sample using Platform Invoke");
SystemTime st = new SystemTime();
LibWrap.GetSystemTime(st);
Console.Write("The Date is: ");
Console.Write("{0} {1} {2}", st.month, st.day, st.year );
}
}
所需的输出:
C# SysTime Sample using Platform Invoke
The Date is: 10 31 2006