Calling MsiEnumRelatedProducts from C# is crashing

2019-06-27 04:29发布

问题:

I'm having no end of trouble calling MsiEnumRelatedProducts from C#. I've tried a couple of variations on the p/invoke definition but no luck (out and ref). I think the problem is the last parameter, which is an LPTSTR that is supposed to point to a string 39 characters long.

Here's the pinvoke and call:

public static string EnumRelatedProducts(string UpgradeCode, int Index)
{
    string ProductCode;
    UInt32 rc = MsiEnumRelatedProducts(UpgradeCode, 0, Index, out ProductCode);
    Console.WriteLine("Returned");
    if (rc != 0)
    {
        return string.Empty;
    }

    return ProductCode;
}

[DllImport("msi.dll", CharSet = CharSet.Auto)]
private static extern UInt32 MsiEnumRelatedProducts(string UpgradeCode, int reserved, int Index, out string ProductCode);

Note that the crash only occurs when the passed UpgradeCode has at least 1 installed product.

回答1:

Try declaring like so:

[DllImport("msi.dll")]
private static extern uint MsiEnumRelatedProducts(
             string lpUpgradeCode, 
             uint dwReserved, 
             uint lProductIndex, 
             StringBuilder lpProductBuf);