SetupVerifyInfFile - 参数不正确。如何使用 C# pinvoke

SetupVerifyInfFile - The parameter is incorrect. How to use C# pinvoke

我有问题 calling/implementing SetupVerifyInfFile
当我调用 VerifyInfFile 函数时,我收到异常 "The parameter is incorrect".

    [DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool SetupVerifyInfFile(
        string FileName,
        IntPtr AltPlatformInfo,
        ref IntPtr InfSignerInfo);

    [StructLayout(LayoutKind.Sequential)]
    public struct SP_INF_SIGNER_INFO
    {
        public int CbSize;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public string CatalogFile;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public string DigitalSigner;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public string DigitalSignerVersion;
    }

    public static void VerifyInfFile(string infPath)
    {
        SP_INF_SIGNER_INFO infSignerInfo = default;
        infSignerInfo.CbSize = Marshal.SizeOf(infSignerInfo);
        var infSignerPtr = Marshal.AllocHGlobal(infSignerInfo.CbSize);

        try
        {
            Marshal.StructureToPtr(infSignerInfo, infSignerPtr, false);
            if (!SetupVerifyInfFile(infPath, IntPtr.Zero, ref infSignerPtr))
                throw new Exception("Error calling SetupVerifyInfFile().", new 
                                     Win32Exception(Marshal.GetLastWin32Error()));
        }
        finally
        {
            Marshal.FreeHGlobal(infSignerPtr);
        }
    }

我可以看到四个明显的错误:

  1. 作为ref IntPtr InfSignerInfo传递的第三个参数。将其作为 ref 传递是错误的。如文档所述,此参数是指向结构的指针。所以你需要删除 ref.
  2. 您没有为 SP_INF_SIGNER_INFO 指定字符集,因此将获得默认字符集 ANSI。这与您的函数声明中的 CharSet.Auto 不匹配。
  3. 您为 CbSize 使用了错误的值。你提供一个指针的大小,但是你需要提供结构体的大小,Marshal.SizeOf(typeof(SP_INF_SIGNER_INFO)).
  4. 您为 MAX_PATH 使用了错误的值。正确的值是 260,而不是 256。