将 ADODB::记录集^ 转换为 _RecordsetPtr

Convert ADODB::Recordset^ to _RecordsetPtr

本文关键字:转换 RecordsetPtr ADODB 记录      更新时间:2023-10-16

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

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

_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;
}