Come posso passare una funzione come riferimento per una richiamata rapporto in C ++ / CLI?
-
23-08-2019 - |
Domanda
Ho qualche codice che gestisce i file di dati e segnala un errore quando si mette nei guai, ma sto avendo problemi a lavorare come dare la mia classe una funzione di callback. Ecco un rapido esempio del tipo di cosa che sto cercando di realizzare:
public delegate void Reporter( System::String^ stringToReport );
/// <summary>
/// Simple file handler with callback options on error
/// </summary>
public ref class MyFileHandler
{
private:
Reporter^ m_reporter;
void ReportError(String^ error)
{
if( m_reporter )
{
m_reporter( error );
}
}
public:
MyFileHandler()
{
}
void SetErrorReporter( Reporter^ reporter )
{
m_reporter = reporter;
}
bool FailingOperation()
{
return false;
}
bool GetData()
{
bool succeeded = false;
// Do some operation that fails
succeeded = FailingOperation();
if( succeeded == false )
{
ReportError( "Gah, something bad happened!" );
}
}
};
public ref class MyFileLoader
{
private:
MyFileHandler m_mfh;
void ErrorHandler(String^ errorMsg)
{
System::Windows::Forms::MessageBox::Show( errorMsg );
}
public:
MyFileLoader()
{
m_mfh.SetErrorReporter( &CallbackFunctionTests::MyFileLoader::ErrorHandler );
}
};
... che ha un problema:
1>CallbackTest.h(131) : error C3374: can't take address of 'CallbackFunctionTests::MyFileLoader::ErrorHandler' unless creating delegate instance
Così ho l'impressione che sono mis-uso o cose malinteso. Forse c'è un modo migliore per raggiungere tale obiettivo?
Soluzione
È necessario creare il delegato esplicitamente - ed è necessario passare l'istanza associata - nel tuo caso, this
- ad esso:
m_mfh.SetErrorReporter(
gcnew Reporter(this, &CallbackFunctionTests::MyFileLoader::ErrorHandler));
Altri suggerimenti
Nel caso in cui qualcuno è interessato, ecco il codice finale (di lavoro):
public delegate void Reporter( System::String^ stringToReport );
/// <summary>
/// Simple file handler with callback options on error
/// </summary>
public ref class MyFileHandler
{
private:
Reporter^ m_reporter;
void ReportError(String^ error)
{
if( m_reporter )
{
m_reporter( error );
}
}
public:
MyFileHandler()
{
}
void SetErrorReporter( Reporter^ reporter )
{
m_reporter = reporter;
}
bool FailingOperation()
{
return false;
}
bool GetData()
{
bool succeeded = false;
// Do some operation that fails
succeeded = FailingOperation();
if( succeeded == false )
{
ReportError( "Gah, something bad happened!" );
}
return succeeded;
}
};
public ref class MyFileLoader
{
private:
MyFileHandler m_mfh;
void ErrorHandler(String^ errorMsg)
{
System::Windows::Forms::MessageBox::Show( errorMsg );
}
public:
MyFileLoader()
{
m_mfh.SetErrorReporter( gcnew Reporter(this, &CallbackFunctionTests::MyFileLoader::ErrorHandler) );
}
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow