We are implementing a number of SDK's for our suite of hardware sensors.
Having successfully got a working C API for one of our sensors, we are now starting the arduous task of testing the SDK to ensure that we haven't introduced any fatal bugs, memory leaks or race conditions.
One of our engineers has reported that when developing the test application (a Qt Widgets application), an issue has occurred when hooking onto a callback which is executed from a separate thread within the DLL.
Here is the callback prototype:
#define API_CALL __cdecl
typedef struct {
// msg fields...
DWORD dwSize;
// etc...
} MSG_CONTEXT, *PMSG_CONTEXT;
typedef void (API_CALL *SYS_MSG_CALLBACK)(const PMSG_CONTEXT, LPVOID);
#define API_FUNC __declspec(dllexport)
API_FUNC void SYS_RegisterCallback(SYS_MSG_CALLBACK pHandler, LPVOID pContext);
And it is attached in Qt as follows:
static void callbackHandler(const PMSG_CONTEXT msg, LPVOID context) {
MainWindow *wnd = (MainWindow *)context;
// *wnd is valid
// Call a function here
}
MainWindow::MainWindow(QWidget *parent) {
SYS_RegisterCallback(callbackHandler, this);
}
My question is this: is the callback executed on the thread which creates it or on the thread which executes it? In either case, I guess it need of some kind of synchronization method. Googling has resulted in a plethora of C# examples, which isn't really whats needed.
One thing under consideration is using the SendMessage
or PostMessage
functions rather than going down the callback route.
Could anyone offer any suggestions please at to how cross-thread safety could be achieved using callbacks? Or is the message pump route the way to go for a Windows-based SDK?