2016-03-02 73 views
0

我在C++/CLI包装器中使用C#dll。该DLL正在返回一个ADODB :: Recordset ^对象,但我需要包装来返回一个_RecordsetPtr对象。 如何在两者之间进行转换?将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; 
} 
+1

一个沉重的阻抗失配。用Marshal :: GetIUnknownForObject()恢复原始接口指针,将IntPtr强制转换为IUnknown *并调用_RecordsetPtr构造函数。一个引用计数太多,我认为,请致电Marshal :: Release() –

回答

1

感谢汉斯帕桑特,我能够找到一个解决方案:

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

您最好检查内存泄漏。编写一个测试应用程序,它可以完成一百万次。 –