0
   DWORD OREnumKey(
      __in         ORHKEY Handle,
      __in         DWORD dwIndex,
      __out        PWSTR lpName,
      __inout      PDWORD lpcName,
      __out_opt    PWSTR lpClass,
      __inout_opt  PDWORD lpcClass,
      __out_opt    PFILETIME lpftLastWriteTime
    );

我的代码

[DllImport("offreg.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern uint OREnumKey(IntPtr Handle, IntPtr dwIndex, [MarshalAs(UnmanagedType.LPWStr)]out StringBuilder lpName, ref IntPtr lpcName, [MarshalAs(UnmanagedType.LPWStr)]out StringBuilder lpClass, ref IntPtr lpcClass, out System.Runtime.InteropServices.ComTypes.FILETIME lpftLastWriteTime);
 IntPtr myKey = hiveid;
    IntPtr dwindex=(IntPtr)0;
    StringBuilder lpName=new StringBuilder("",255);
    IntPtr lpcName = (IntPtr)0;
    StringBuilder  lpClass=new StringBuilder("",255);
    IntPtr lpcClass = (IntPtr)11;
    System.Runtime.InteropServices.ComTypes.FILETIME lpftLastWriteTime;
    uint ret3 = OREnumKey(myKey, dwindex, out lpName, ref lpcName, out lpClass, ref lpcClass, out lpftLastWriteTime);

ret3=ERROR_MORE_DATA 234 问题可能是错误的 StringBuilder 大小或 FILETIME 2nd 我应该如何从 C# 调用 PWSTR 参数? [MarshalAs(UnmanagedType.LPWStr)]out StringBuilder lpName这是正确的吗?

4

1 回答 1

1

这是一个非常标准的 Windows 错误代码,这意味着您调用了一个 winapi 函数并且您没有传递足够大的缓冲区。解决问题的唯一方法是传递更大的缓冲区。

这看起来很像 RegQueryKeyEx() 的包装器,这使得您很可能将错误数据传递给函数。lpcName参数实际上是ref int而不是 IntPtr。你应该传递一个变量来存储你传递的缓冲区的大小,在你的例子中是 255。lpcClass 参数同样是无聊的。这应该解决它:

[DllImport("offreg.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern uint OREnumKey(
    IntPtr Handle, 
    int dwIndex,
    StringBuilder lpName, 
    ref int lpcName, 
    StringBuilder lpClass, 
    ref int lpcClass, 
    out System.Runtime.InteropServices.ComTypes.FILETIME lpftLastWriteTime);

    ...   
    StringBuilder lpName=new StringBuilder("",255);
    int nameSize = lpName.Capacity;
    StringBuilder  lpClass=new StringBuilder("",255);
    int classSize = lpClass.Capacity;
    System.Runtime.InteropServices.ComTypes.FILETIME lpftLastWriteTime;
    uint ret3 = OREnumKey(hiveid, 0, lpName, ref nameSize, lpClass, ref classSize, out lpftLastWriteTime);
    if (ret3 != 0) throw new Exception("kaboom");
    string name = lpName.ToString();
    string className = lpClass.ToString();
于 2012-05-30T14:15:34.043 回答