将 ADODB::Recordset^ 转换为 _RecordsetPtr

Convert ADODB::Recordset^ to _RecordsetPtr

我在 C++/CLI 包装器中使用 C# dll。该 dll returning 一个 ADODB::Recordset^ 对象,但我需要 return 一个 _RecordsetPtr 对象的包装器。 如何在两者之间转换?

这是我目前所拥有的。我遇到的 运行 问题是在 for 循环的最后一行之后,函数跳到 return 语句并结束。它不会继续循环,也不会到达 "Object^ rows = . . ." 行。

_RecordsetPtr TraserInterface::GetDistributorRecordset()
{
    ADODB::Recordset^ recordset = TraserWrapper::Instance->traserInterface->DistributorRecordset;
    ADODB::Fields^ fields = ((ADODB::RecordsetClass^)recordset)->default;
    HRESULT hr;
    _RecordsetPtr recordsetPtr("ADODB.Recordset");
    for (int i = 0; i < fields->Count; i++)
    {
        ADODB::Field^ field = fields[i];
        String^ fieldName = field->Name;
        _bstr_t bstrName = MarshalString(fieldName).c_str();
        int type = (int)field->Type;
        int definedSize = field->DefinedSize;
        int fieldAttrib = field->Attributes;
        hr = recordsetPtr->Fields->Append(bstrName, (DataTypeEnum)type, definedSize, (FieldAttributeEnum)fieldAttrib);
    }
    Object^ rows = recordset->GetRows((int)ADODB::GetRowsOptionEnum::adGetRowsRest, (Object^)ADODB::BookmarkEnum::adBookmarkFirst, (Object^)fields);
    // loop through rows and populate recordsetPtr . . .
    return recordsetPtr;
}

感谢 Hans Passant,我找到了解决方案:

_RecordsetPtr TraserInterface::GetDistributorRecordset()
{
    ADODB::Recordset^ recordset = TraserWrapper::Instance->traserInterface->DistributorRecordset);
    IntPtr recordsetIntPtr = Marshal::GetIUnknownForObject(recordset);
    IUnknown* unknown = (IUnknown*)(void*)recordsetIntPtr;
    _RecordsetPtr recordsetPtr(unknown);
    return recordsetPtr;
}