【发布时间】: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()