【问题标题】:Convert ADODB::Recordset^ to _RecordsetPtr将 ADODB::Recordset^ 转换为 _RecordsetPtr
【发布时间】:2016-06-15 16:58:04
【问题描述】:

我在 C++/CLI 包装器中使用 C# dll。 dll 返回一个 ADODB::Recordset^ 对象,但我需要包装器返回一个 _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;
}

【问题讨论】:

  • 严重的阻抗不匹配。使用 Marshal::GetIUnknownForObject() 恢复原始接口指针,将 IntPtr 转换为 IUnknown* 并调用 _RecordsetPtr 构造函数。我认为一个引用计数太多,调用 Marshal::Release()

标签: c# c++ adodb recordset


【解决方案1】:

感谢 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;
}

【讨论】:

  • 你最好检查一下内存泄漏。编写一个小测试应用程序,执行一百万次。
猜你喜欢
  • 1970-01-01
  • 2016-08-13
  • 2016-10-10
  • 1970-01-01
  • 1970-01-01
  • 2015-09-09
  • 1970-01-01
  • 2016-01-14
  • 2019-03-21
相关资源
最近更新 更多