C# 如何将UDT的SAFEARRAY从C传递给未匹配的代码#
我还使用了VT_记录。 但没有成功通过一系列UDTC# 如何将UDT的SAFEARRAY从C传递给未匹配的代码#,c#,c++,unmanaged,managed,safearray,C#,C++,Unmanaged,Managed,Safearray,我还使用了VT_记录。 但没有成功通过一系列UDT [ComVisible(true)] [StructLayout(LayoutKind.Sequential)] public class MY_CLASS { [MarshalAs(UnmanagedType.U4)] public Int32 width; [MarshalAs(UnmanagedType.
[ComVisible(true)]
[StructLayout(LayoutKind.Sequential)]
public class MY_CLASS
{
[MarshalAs(UnmanagedType.U4)]
public Int32 width;
[MarshalAs(UnmanagedType.U4)]
public Int32 height;
};
[DllImport("mydll.dll")]
public static extern Int32 GetTypes(
[In, Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_RECORD, SafeArrayUserDefinedSubType = typeof(MY_CLASS))]MY_CLASS[] myClass,
[In, Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_RECORD, SafeArrayUserDefinedSubType = typeof(Guid))]Guid[] guids
);
如果我在没有第一个参数的情况下与非托管代码通信,那么将“guids”参数传递给非托管代码时不会出错
我还能够将非托管端获得的SAFEARRAY元素强制转换为GUID类型。
但是,如果我尝试使用SAFEARRAY将我的UDT类my_类传递给非托管代码,那么它在托管代码上失败。(如上代码片段)
它显示异常“myapp.exe中发生了类型为'System.Runtime.InteropServices.SafeArrayTypeMismatchException'的未处理异常”
“其他信息:指定的数组不是预期的类型。”
在这种情况下,请帮助我将UDT的安全数组传递给未匹配的代码。我找到了一个解决此问题的方法。
我试着用另一种方法来解决这个问题。 我将具有SAFEARRAYs作为其成员的UDT传递给非托管代码 下面是我遵循的托管代码
[ComVisible(true)]
[StructLayout(LayoutKind.Sequential)]
public class MY_CLASS
{
[MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.I4)]
public Int32[] width;
[MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.I4)]
public Int32[] height;
};
[DllImport("mydll.dll")]
public static extern Int32 GetTypes(
[In, Out] MY_CLASS myClass
);
在非托管方面
typedef struct _MY_STRUCT
{
SAFEARRAY * pWidths;
SAFEARRAY * pHeights;
}MY_STRUCT;
HRESULT GetTypes(MY_STRUCT * pMyStruct)
{
// Here I can use pMyStruct->pWidths or pMyStruct->pHeights
// paramater as safearray of int32 type.
// I can modify it's element and it will be visible
// on managed side.
return S_OK;
}
我使用这种类型的机制传递具有值类型数组的UDT,而不是传递UDT数组
[ComVisible(true)]
[StructLayout(LayoutKind.Sequential)]
public class MY_CLASS
{
[MarshalAs(UnmanagedType.U4)]
public Int32 width;
[MarshalAs(UnmanagedType.U4)]
public Int32 height;
};
[DllImport("mydll.dll")]
public static extern Int32 GetTypes(
[In, Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_RECORD, SafeArrayUserDefinedSubType = typeof(MY_CLASS))]MY_CLASS[] myClass,
[In, Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_RECORD, SafeArrayUserDefinedSubType = typeof(Guid))]Guid[] guids
);