【问题标题】:PInvoke in WinRT results in Error _NO_TOKEN(1008)WinRT 中的 PInvoke 导致错误 _NO_TOKEN(1008)
【发布时间】:2013-11-07 15:37:30
【问题描述】:

我正在尝试使用 PInvoke 和 .Net4.5 访问电池设备信息(在 Enumerating Battery Devices 行)。我有一个 WPF 应用程序运行良好,并且能够获取各种低级电池信息。

现在我正在尝试将同一个应用程序修改为 WinRT 现代应用程序。 Win32 API(例如 SetupDiEnumDeviceInterfaces、SetupDiGetDeviceInterfaceDetail)在 WinRT 中运行良好。但是当涉及到 CreateFile 时,我得到了无效的句柄 (-1) 并且 Marshal.GetLastWin32Error() 给出了 1008 (Error_No_Token)。 Marshal.GetHRForLastWin32Error().ToString() 给出“-2147023888”

知道如何在 WinRT 中通过 PIvoke 使用 CreateFile 吗?

[DllImport ("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
    internal static extern IntPtr CreateFile(
      string lpFileName,
      uint dwDesiredAccess,
      uint dwShareMode,
      IntPtr SecurityAttributes,
      uint dwCreationDisposition,
      uint dwFlagsAndAttributes,
      IntPtr hTemplateFile
      );

   //var hBattery = NativeMethods.CreateFile (devicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, FileAttributes.Normal, IntPtr.Zero);
    var hBattery = NativeMethods.CreateFile (devicePath, 3, 3, IntPtr.Zero, 3, 128, IntPtr.Zero);
    if ( hBattery == new IntPtr (-1) )
    { throw new System.Exception(Marshal.GetHRForLastWin32Error().ToString()); }

【问题讨论】:

  • 不能调用 CreateFile,沙盒不允许。对于文件,您必须使用 Windows.Storage 命名空间中的新 Windows 运行时 API。对于其他设备,除非有新的 api 可用,否则您将不走运。试试msdn.microsoft.com/en-us/library/windows/apps/… 命名空间。
  • 谢谢克里斯。如果您可以将相同的评论作为答案,我很乐意将其标记为已接受的答案。它实际上引导我朝着正确的方向前进。

标签: c# .net windows-runtime pinvoke .net-4.5


【解决方案1】:

知道如何在 WinRT 中通过 p/invoke 使用 CreateFile 吗?

你不能这样做。 WinRT 限制了允许用户代码调用的 API,该函数在 WinRT 中不可用。 documentation for CreateFile 声明限制如下:

要求

支持的最低客户端:Windows XP [仅限桌面应用]

支持的最低服务器:Windows Server 2003 [仅限桌面应用]

文本仅限桌面应用程序表示WinRT不提供

在 WinRT 上,您应该使用富有想象力的 CreateFile2。看看它的要求:

要求

最低支持客户端:Windows 8 [桌面应用程序 | Windows 应用商店应用]

最低支持服务器:Windows Server 2012 [桌面应用程序 | Windows 应用商店应用]

文本Windows 应用商店应用程序 表示该功能可用于 WinRT 代码。

使用 WinRT 时,有大量传统的 Windows API 不可用。在尝试调用 API 函数之前,您应该养成检查文档需求部分的习惯。

【讨论】:

  • 谢谢戴夫!我开始阅读更多关于商店应用程序部分的细则。但限制并不完全正确,请参阅gerhas.netii.net/wordpress/?p=45 示例。我尝试了 CreateFile2,并收到拒绝访问错误。这次文档是正确的,“当从 Windows 应用商店应用程序调用时,CreateFile2 被简化。您只能打开 ApplicationData.LocalFolder 或 Package.InstalledLocation 目录中的文件或目录。”我想我必须使用 Windows.Devices.Custom 路线。
  • 我认为我的回答是准确的
猜你喜欢
  • 1970-01-01
  • 2014-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-29
相关资源
最近更新 更多