'C++/CLI callback to C#
I have a C library (DLL) where I have callback functions with defined datatypes.
Now I am writing Wrapper(DLL) for this in C++/CLI. This Wrapper Dll will be used in my C# application.
How to Implement the callback in C++/CLI so that i can write the call back function in C# an passt it through the wrapper to the C librarby.
Dll Libray ...
# C libary (DLL) *.h file
...
typedef void (*TOnMonitoringStateCB)(const ROBOT_STATE);
typedef void (*TOnMonitoringDataCB)(const LPMONITORING_DATA);
...
DRFL_API void _SetOnMonitoringState(LPROBOTCONTROL pCtrl, TOnMonitoringStateCB pCallbackFunc);
DRFL_API void _SetOnMonitoringData(LPROBOTCONTROL pCtrl, TOnMonitoringDataCB pCallbackFunc);
...
class CDRFL
{
public:
// robot status data
void SetOnMonitoringState(TOnMonitoringStateCB pCallbackFunc) { _SetOnMonitoringState(_rbtCtrl, pCallbackFunc); };
// robot operating data
void SetOnMonitoringData(TOnMonitoringDataCB pCallbackFunc) { _SetOnMonitoringData(_rbtCtrl, pCallbackFunc); };
...
Wrapper (DLL) C++/CLI ...
# C++/CLI *.h (my try)
...
public delegate void ManagedTOnMonitoringStateCB(const RobotState);
public delegate void ManagedTOnMonitoringDataCB(const LpMonitoringDate);
...
public ref class WrapperClass
{
...
void SetOnMonitoringState(ManagedTOnMonitoringStateCB^ callbackFunc);
void SetOnMonitoringData(ManagedTOnMonitoringDataCB^ callbackFunc);
...
}
# *.cpp (my try)
...
void WrapperClass::SetOnMonitoringState(ManagedTOnMonitoringStateCB^ callbackFunc)
{
IntPtr cbPtr = System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(callbackFunc);
_rbtCtrl->SetOnMonitoringState(static_cast<CLibrarbyc::TOnMonitoringStateCB>(cbPtr.ToPointer()));
};
void WrapperClass::SetOnMonitoringData(ManagedTOnMonitoringDataCB^ callbackFunc)
{
IntPtr cbPtr = System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(callbackFunc);
_rbtCtrl->SetOnMonitoringData(static_cast<CLibrarbyc::TOnMonitoringDataCB>(cbPtr.ToPointer()));
};
...
C# ...
...
_rbtCtrl.SetOnMonitoringState(OnMonitoringState());
void OnMonitoringState()
{
textBox1.AppendText("...");
}
_rbtCtrl.SetOnMonitoringData(OnMonitoringData());
void OnMonitoringData()
{
textBox1.AppendText("...");
}
...
The C++/CLI seems to be OK, but in the C# part I always have problems with the Converting the types. It also can be a problem of the initialisaten of the callbackfunction and the handling of the function in C#. But maybe there is also and erro in the C++/CLI Wrapper or it can be done easier, but it compiles.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
