我遇到了terminating _variant_t types
的麻烦,它触发了一个断点,程序崩溃了,
引起麻烦的代码部分如下:
double ConnectToHYSYS::GetExergy() {
//In this method, I'm using early Binding, so no more Dispatchs, lets get the interfaces themselves
int i;
HRESULT hr = hyStream->QueryInterface(IID_PPV_ARGS(&hyBackDoor));
if (SUCCEEDED(hr)) {
cout << "Got the BackDoor safely" << endl;
// Get Array of CorrelationNames but in type _variant_t
_variant_t t = _variant_t("HysysCorrelation.300.[]:Name.0");
InternalVariableWrapper = hyBackDoor->GetBackDoorTextVariable(&t);
TextFlexVariable = InternalVariableWrapper->GetVariable();
_variant_t CorrelationNames= TextFlexVariable->GetValues();
//Conversion of _variant_t type to safe Array
SAFEARRAY *psa;
psa = CorrelationNames.parray;
// Loop through safeArray of BSTR
BSTR* pVals;
HRESULT hr = SafeArrayAccessData( psa, (void**)&pVals ); // direct access to SA memory
if( SUCCEEDED( hr ) )
{
long lowerBound, upperBound; // get array bounds
SafeArrayGetLBound( psa, 1, &lowerBound );
SafeArrayGetUBound( psa, 1, &upperBound );
long cnt_elements = upperBound - lowerBound + 1;
for( i = 0; i < cnt_elements; ++i ) // iterate through returned values
{
BSTR lVal = pVals[ i ];
//Convert to normal String for comparison with Mass Exergy
string CorrelationFinal= ConvertBSTRToMBS( lVal );
std::cout << "element " << i << ": value = " << CorrelationFinal << std::endl;
if( CorrelationFinal == "Mass Exergy" ){ break; }
}
SafeArrayUnaccessData( psa );
}
SafeArrayDestroy( psa );
if (SUCCEEDED(hr)) {
cout << "Got the BackDoor Text Variable safely" << endl;
}
if (FAILED(hr)) {
cout << "Couldnt get the BackDoor Text Variable" << endl;
}
}
if (FAILED(hr)) {
cout << "Couldnt get the BackDoor" << endl;
}
// Get Exergy Moniker
string str = to_string(i);
string ExergyMoniker ="HysysCorrelation.300." + str + ":ExtraData.550.0";
// OLE accepts only _variant_t type and we need char array for that conversion... converting string to char array
char tab2[ 1024 ];
strncpy_s( tab2, ExergyMoniker.c_str(), sizeof( tab2 ) );
tab2[ sizeof( tab2 ) - 1 ] = 0;
//Get the exergy itself
_variant_t t = _variant_t( tab2 );
InternalVariableWrapper = hyBackDoor->GetBackDoorVariable( &t );
RealVariable = InternalVariableWrapper->GetVariable();
_variant_t ExergyValue = RealVariable->GetValue( "kJ/kg" );
double ExergyValueDouble = ExergyValue.dblVal;
return ExergyValueDouble;
那么,任何想法为什么会导致这种错误?当我单击“中断”时,它指向此内联代码(comutil.h)
inline _variant_t::~_variant_t() throw()
{
::VariantClear(this);
}
另外,当我在调试过程中单击继续时,程序将继续正常运行,这是否意味着我可以处理该异常?
最佳答案
您的代码中存在许多潜在问题,例如,您的所有方法GetBackDoorTextVariable(),GetValues(),GetBackDoorVariable(),GetValue()可能会生成错误的变体。
但是,似乎没有什么可以解决的一件事是如何处理CorrelationNames
实例。
因为_variant_t
是一个自动包装器类,并为您处理内存释放,所以您不应该过分使用它。但是在您的代码中,无需将SafeArrayDestroy
成员设置为null,就可以释放此变体所保存的内存(通过parray
调用)。析构函数运行时,它将尝试释放空指针并崩溃。
因此,删除SafeArrayDestroy(psa)
行,它应该更好地工作,至少对于此问题而言。