Marshaling CTL_USAGE

时间:2013-05-08 14:18:53

标签: c# interop marshalling

我正在做一个使用证书工作的项目,我需要将CTL_USAGE结构转换为C#。原始结构如下:

typedef struct _CTL_USAGE {
  DWORD cUsageIdentifier;
  LPSTR *rgpszUsageIdentifier;
} CTL_USAGE, *PCTL_USAGE, CERT_ENHKEY_USAGE, *PCERT_ENHKEY_USAGE;

根据P / Invoke网站,C#结构应为:

[StructLayout(LayoutKind.Sequential)]
public struct CTL_USAGE
{
    public int cUsageIdentifier;
    public IntPtr rgpszUsageIdentifier;
}

要使用此代码,我使用Encoding.ASCII.GetBytes()将我想要添加到结构的每个字符串转换为字节数组。然后我使用GCHandle.Alloc(byteArray,GCHandleType.Pinned)将该字节数组转换为GCHandle。我将该值添加到IntPtrs数组,然后创建一个到IntPtr数组的GCHandle并将其分配给rgpszUsageIdentifier。对CryptEncodeObjectEx的调用不会引发错误,但结果数据是垃圾,无法使用CryptDecodeObject进行未加密。我的编码如下:

//EnhancedUsage is a List<String> containing the Enhanced Usage OIDs
CTL_USAGE usage = new CTL_USAGE()
{
    cUsageIdentifier = EnhancedUsage.Count,
};

List<IntPtr> usageList = new List<IntPtr>();

foreach (string s in EnhancedUsage)
    usageList.Add(new PinnedHandle(Encoding.ASCII.GetBytes(s)));

usage.rgpszUsageIdentifier = new PinnedHandle(usageList.ToArray());

IntPtr data = Marshal.AllocHGlobal(Marshal.SizeOf(usage));
Marshal.StructureToPtr(usage, data, false);

int encodedSize = 0;

if (!Crypt32.CryptEncodeObjectEx((int)CertEncoding.X509Asn, CertOid.szOID_ENHANCED_KEY_USAGE, data, 0, IntPtr.Zero, null, ref encodedSize))
    throw new Win32Exception();

byte[] buffer = new byte[encodedSize];

if (!Crypt32.CryptEncodeObjectEx((int)CertEncoding.X509Asn, CertOid.szOID_ENHANCED_KEY_USAGE, data, 0, IntPtr.Zero, buffer, ref encodedSize))
    throw new Win32Exception();

PinnedHandle类是GCHandle的包装器。它看起来像这样:

public class PinnedHandle : IDisposable
{
    private GCHandle handle;

    public PinnedHandle(object value)
    {
        handle = GCHandle.Alloc(value, GCHandleType.Pinned);
    }

    public static implicit operator IntPtr(PinnedHandle value)
    {
        return value.handle.AddrOfPinnedObject();
    }

    public void Dispose()
    {
        try
        {
            handle.Free();
        }
        catch
        {

        }
    }
}

我认为这不会引起任何问题,因为我已经在其他类似的情况下使用它并且它们正常工作。知道如何使这项工作正常吗?

1 个答案:

答案 0 :(得分:1)

使用AllocHGLobal分配非托管内存块,将所有IntPtr实例从usageList复制到它,并将此块句柄传递给非托管函数。请使用Marshal.WriteIntPtr Method (IntPtr, Int32, IntPtr)

http://msdn.microsoft.com/en-us/library/ms146679.aspx

在我的互操作性代码中,我避免固定托管对象,而更喜欢使用不同的Marshal方法构建本机内存区域。