如何从.Net中的COM类获取自定义结构(UDT)数组?

时间:2012-10-02 11:39:03

标签: .net com interop com-interop vb.net-2010

我有一个COM类(用C ++开发,以防万一),它有一个方法“GetStructList”,它应该返回一些自定义类型的列表,我正在开发一个.NET应用程序,应该得到它列表。

我控制COM类代码以及应用程序,我无法获取数据。

COM类代码:

1- IDL:

HRESULT GetList([in,out] SAFEARRAY(struct MyStruct)* myStructs);
// I have also tried with [out] instead of [in, out]

[uuid(628913FC-CC26-1654-472F-0B70CC39DEE0)]
struct MyStruct
{
    int myInt;
    DOUBLE myDouble;

};

2- CPP:

STDMETHODIMP MyClass::GetList(SAFEARRAY** myStructs)
{
    SAFEARRAY* psa = *myStructs;
    SAFEARRAYBOUND sab = {someSize, 0};
    MyStruct *pData;
    IRecordInfo *pRI;
    HRESULT hr;

    hr = GetRecordInfoFromGuids(LIBID_MyCOMLib, 1, 0, 0x409, __uuidof(MyStruct), &pRI);
    psa = SafeArrayCreateEx(VT_RECORD, 1, &sab, pRI);
    pRI->Release();
    pRI = NULL;
    hr = SafeArrayAccessData(psa, (void**)&pData);
    for (size_t i = 0; i < someSize; i++) 
    {
        pData[i].myInt = someInt;
        pData[i].myDouble = somedouble;
    }
    hr = SafeArrayUnaccessData(psa);

    return S_OK;
}

.Net Code(VB):

Option Strict
...
<MarshalAs(UnmanagedType.SafeArray, safearraysubtype:=VarEnum.VT_RECORD)>
Private m_List As MyStruct()

Private Sub btnGetList_Click(sender As System.Object, e As System.EventArgs) 
    Dim m_List() As MyStruct
    m_ComObject.GetList(m_List) 

    ' I have tried several other things, getting different errors with each of them'
    'm_ComObject.GetList(CType(m_List, Array))'

    'Dim structs() As MyStruct'
    'Dim arr as System.Array = structs '
    'm_ComObject.GetList(arr)'

    For Each o In cortes
        Dim s As MyStruct = CType(o, MyStruct)
        MsgBox(s.myInt)
        Exit For
    Next
End Sub

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

生成的互操作签名是什么?

你得到了什么确切的错误?

COM接口中的myStruct参数应为[out],而不是[in, out]

是部分:

Dim m_List() As SceneCutInfo
m_ComObject.GetList(m_List) 

意思是:

Dim m_List() As MyStruct
m_ComObject.GetList(m_List) 

但是,除非你有充分的理由使用SAFEARRAY(例如自动化兼容接口),否则我建议使用普通数组,因为不需要与VT_RECORD进行对抗。