How to implement OOBE complete notification in c++? - c++

I want to do a win32 implementation of RegisterWaitUntilOOBECompleted API for my app.
The goal is to detect OOBE complete and perform specific operations.
However, I don't quite understand how to implement it in c++ code.
I spent the past 6 hours looking for sample implementation but to no luck.
Can anyone explain how to do it?
Registers a callback to be called once OOBE (Windows Welcome) has been
completed.
Syntax C++
BOOL RegisterWaitUntilOOBECompleted( OOBE_COMPLETED_CALLBACK
OOBECompletedCallback, PVOID CallbackContext,
PVOID *WaitHandle );
Parameters
OOBECompletedCallback
Pointer to an application-defined callback function that will be
called upon completion of OOBE. For more information, see
OOBE_COMPLETED_CALLBACK.
CallbackContext
Pointer to the callback context. This value will be passed to the
function specified by OOBECompletedCallback. This value can be nulll.
WaitHandle
Pointer to a variable that will receive the handle to the wait
callback registration.

For anyone in the future who might be looking for sample implementation of this API, here's how I did it. This sample code is not intended to compile though.
Header file
#include "Oobenotification.h"
class MainClass
{
// put constructor here
// destructor
~MainClass();
// OOBE notification
OOBE_COMPLETED_CALLBACK OOBECompletedCallback;
PVOID m_OOBEHandle = NULL;
// receive notification one OOBE complete
void OOBERegisterNotification();
static void CALLBACK NotifyOOBEComplete(PVOID CallbackContext);
public:
Init();
};
CPP file
#include "header.h"
void MainClass::~MainClass()
{
if (m_OOBEHandle != NULL)
UnregisterWaitUntilOOBECompleted(m_OOBEHandle);
}
void MainClass::Init()
{
// register to receive oobe complete notification
OOBERegisterNotification();
}
void MainClass::OOBERegisterNotification()
{
OOBECompletedCallback = &NotifyOOBEComplete;
BOOL bRes = ::RegisterWaitUntilOOBECompleted(OOBECompletedCallback, NULL, &m_OOBEHandle);
if (!bRes)
{
// handle failed registration here
}
}
void CALLBACK MainClass::NotifyOOBEComplete(PVOID Context)
{// async
UNREFERENCED_PARAMETER(Context);
// what you want to do after OOBE
}

Related

GetDlgItemText and Multithreading

So I have been trying to implement the concept of multithreading to an MFC application I am making. I used the method suggested here. It works fine but I am having an issue with using data given by the user while the thread is working.
I'll explain.
I am making a simple GUI to send and receive data over a serial port. So the data in IDC_SEND is user-input, and is then sent through the serial port. I am using the WINAPI definition of GetDlgItemText, but since the controlling function for AfxBeginThread is defined as a static function I cannot do this. So I tried ::GetDlgItemText, but that calls the CWnd definition which takes one or three or four(?) arguments.
So ::GetDlgItemText(IDC_SEND, CString text) doesn't work. This problem continues for SetDlgItemText too.
I have tried getting the data outside my controlling function, but since it is defined to return a UINT type, I cannot get the received data out.
The relevant code
void CCommTest2Dlg::OnButton()
{
THREADSTRUCT *_param = new THREADSTRUCT;
_param->_this = this;
AfxBeginThread (StartThread, _param);
}
UINT CCommTest2Dlg::StartThread(LPVOID param)
{
THREADSTRUCT* ts = (THREADSTRUCT*)param;
AfxMessageBox ("Thread is started!");
//Opened Serial Port
//Writing data from Editbox
CString text;
::GetDlgItemText(IDC_SEND,text);//********ERROR HERE!!
serial.Write(text);
//At Receiver port data is wriiten into CString a.
CString a;
::SetDlgItemText( IDC_RECV, a);//Apparently this calls the SetDlgItemText from the CWnd class, and not the Windows API that takes more than one argument.
AfxMessageBox ((LPCTSTR)a);//This works, but I need the data in the EditBox.
//Closing Ports
delete ts; //Edit 1
return 1;}
A few definitions:
static UINT StartThread (LPVOID param);
//structure for passing to the controlling function
typedef struct THREADSTRUCT
{
CCommTest2Dlg* _this;
} THREADSTRUCT;
UINT StartThread(void);
Any thoughts?
PS: Also Edit 1 at the end was added by me as I read that this implementation could result in memory leaks. Does it look like the addition might have fixed that?

How to properly delete a pointer to callback function.

I have a MainProgram.exe which calls in to MyDll.dll and uses curl to receive data on a callback function.
I have wrapped curl in a function called CurlGetData which creates a curl instance and performs curl_easy_perform.
Here is my code:
//Interface class to derive from
class ICurlCallbackHandler
{
public:
virtual size_t CurlDataCallback( void* pData, size_t tSize ) = 0;
};
//Class that implements interface
class CurlCallbackHandler : public ICurlCallbackHandler
{
public:
bool m_exit = false;
virtual size_t CurlDataCallback( void* pData, size_t tSize ) override
{
if(m_exit)
return CURL_READFUNC_ABORT;
// do stuff with the curl data
return tSize;
}
}
CurlCallbackHandler *m_curlHandler;
//Create an instance of above class in my dll constructor
MyDll:MyDll()
{
m_curlHandler = new CurlCallbackHandler();
}
//Cleanup above class in my dll destructor
MyDll:~MyDll()
{
delete m_curlHandler;
m_curlHandler = nullptr;
}
//Function to start receiving data asynchronously
void MyDll::GetDataAsync()
{
std::async([=]
{
//This will receive data in a new thread and call CurlDataCallback above
//This basically calls easy_perform
CurlGetData(m_curlHandler);
}
}
//Will cause the curl callback to return CURL_READFUNC_ABORT
void MyDll::StopDataAsync()
{
m_curlHandler->m_exit = true;
}
The function GetDataAsync is called from my main program and it basically calls curl_easy_perform and uses the m_curlHandler as its callback function which calls back up into CurlDataCallback.
This all works fine but whenever my main program exits, it calls MyDll::StopDataAsync which stops the curl data callback and then the destructor of MyDll is called which cleans up the m_curlHandler.
But I find that at that moment curl has not yet finished with this call back and the program crashes as m_curlHandler has been deleted but the curl callback in the new async thread still is using it.
Sometimes it closes down fine but other times it crashes due to the curlcallback trying to access a pointer that has been deleted by the destructor.
How can I best clean up the m_curlHandler? I want to avoid putting in wait time-outs as this this will affect the performance of my main program.
According to the C++ standard the MyDll::GetDataAsync() function should not return immediately, it should block until the asynchronous thread has finished, which would effectively make the operation synchronous. However I believe Microsoft intentionally violated this part of the std::async specification, so actually it does return immediately, and it's possible for you to destroy the callback while the async thread is still using it (which is exactly the problem that would be avoided if the Microsoft implementation followed the standard!)
The solution is to keep hold of the std::future that std::async returns, and then block on that future (which ensures the async thread has finished) before destroying the callback.
class MyDLL
{
std::future<void> m_future;
...
};
MyDll:~MyDll()
{
StopDataAsync();
m_future.get(); // wait for async thread to exit.
delete m_curlHandler; // now it's safe to do this
}
//Function to start receiving data asynchronously
void MyDll::GetDataAsync()
{
m_future = std::async([=]
{
//This will receive data in a new thread and call CurlDataCallback above
//This basically calls easy_perform
CurlGetData(m_curlHandler);
}
}
N.B. your m_exit member should be std::atomic<bool> (or you should use a mutex to protect all reads and writes to it) otherwise your program has a data race and so has undefined behaviour.
I would also use std::unique_ptr<CurlCallbackHandler> for m_curlHandler.
I want to avoid putting in wait time-outs as this this will affect the performance of my main program.
The solution above will cause your destructor to wait, but only for as long as it takes for the callback to notice that m_exit == true and cause the async thread to stop running. That means you only wait as long as necessary and no longer, unlike time-outs which would mean guessing how long is "long enough", and then probably adding a bit more to be safe.

How to return value from asynchronous function in dll

My dll has asynchronous function which starts a thread and returns immediately. It accepts handle of event object (type HANDLE) which the thread signals when it is done. This works fine but how can I return result from the function that it passed and no error occurred? A simple bool type will do.
I am thinking of using GetLastError() kind of call to get result of last function but I am not really sold on this way. I also looked at std::future and std::async but I am not sure if I can use that in dll function!? Another option I thought about is to use GetOverlappedResultbut that works usually with file i/o and I don't know if I can use this for a custom function that I have written.
Chad is right callback is safe and easy way to do it
// DLL:
__declspec(dllexport) void (*callback_function)(DWORD ret)=NULL;
DWORD _stdcall thread_function(LPVOID p)
{
// do something ...
if (callback_function) callback_function(some_return_value);
}
// DLL usage
DWORD return_value1=0;
bool done1=false;
void callback_function1(DWORD ret)
{
return_value1=ret;
done1=true;
}
void main()
{
callback_function=callback_function1; // set callbak function for DLL
done1=false; // invalidate return value
// here call you DLL function
for (;!done1;) Sleep(1); // wait for valid result ... also can add some timeout to avoid hang-ups
// now in return_value1 is the valid return value
}
also you can use waitforsingleobject instead
http://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx

Cannot lock Qt mutex (QReadWriteLock) Access violation writing

Some background for this question is my previous question:
non-member function pointer as a callback in API to member function (it may well be irrelevant).
The callback launches a thread that writes some data. There is another thread that reads the same data, and that results in some crashes.
I just took a crash course in multi-threading (thanks SO), and here is my attempt to guarantee that the data isn't accessed by the writer and the reader at the same time. I'm using some mutex mechanism from Qt (QReadWriteLock).
#include <QSharedPointer>
#include <QReadWriteLock>
Class MyClass
{
public:
MyClass();
bool open();
float getData();
void streamCB(void* userdata);
protected:
float private_data_;
QSharedPointer<QReadWriteLock> lock_;
};
// callback wrapper from non-member C API to member function void
__stdcall streamCBWrapper(void* userdata)
{
static_cast<MyClass*>(userdata)->streamCB(userdata);
}
// constructor
MyClass::MyClass()
{
lock_ = QSharedPointer<QReadWriteLock>(new QReadWriteLock());
lock_->lockForWrite();
private_data_ = getData();
lock_->unlock();
}
// member callback
void MyClass:streamCB(void* userdata)
{
float a = getData();
lock_->lockForWrite(); //*** fails here
private_data_ = a;
lock_->unlock();
}
I have a segmentation fault while running the program. The VS debugger says Access violation writing location 0x00fedbed. on the line that I marked //*** fails here.
The lock worked in the constructor, but not in the callback.
Any idea what goes wrong? What should I look at? (and how can I refine my question)
Thanks!
Other relevant thread
Cannot access private member declared in class 'QReadWriteLock'Error 1 error C2248: 'QReadWriteLock::QReadWriteLock' (I used the QSharedPointer suggestion)
Edit 1:
The callback is set up
bool MyClass::open()
{
// stuffs
int mid = 0;
set_stream_callback(&streamCBWrapper, &mid);
// more stuffs
return true;
}
Edit 2:
Thank you for all the suggestions.
So my mistake(s) may not be due at all to the mutex, but to my lack of understanding of the API? I'm quite confused.. Here is the API doc for the set_stream_callback.
typedef void (__stdcall *STREAM_CALLBACK)(void *userdata);
/*! #brief Register a callback to be invoked when all subscribed fields have been updated
*
* #param streamCB pointer to callback function
* #param userdata pointer to private data to be passed back as argument to callback
* #return 0 if successful, error code otherwise
*/
__declspec(dllimport) int __stdcall set_stream_callback(
STREAM_CALLBACK streamCB, void *userdata);
Good example why sufficient code example is required.
If I interpret your callback syntax correctly,
set_stream_callback(&streamCBWrapper, &mid);
sets streamCBWrapper as callback function, while &mid is the pointer to userdata.
In the callback, you are actually now casting a pointer to int to MyClass, then try to access a member variable of a non-existant object.
Make sure to pass an instance of MyClass to your callback. I assume this would be this in your case.
Sounds fundamentally like a threading issue to me. Since you're using the Qt mutexing anyway, you might consider using Qt's threading mechanisms and sending signals and slots between the threads. They're pretty well documented and easy to use as long as you follow the suggestions here and here.

How to use callback results in asynchronous model C++

I have a C++ API which has a certain defined functions and it's related callbacks.
All these functions are asynchronous in nature.
Now, using this API I want to construct an asynchronous system which sends
multiple request to the server for collecting different data items and then use
these data item for further use.
For example:
void functionA()
{
requestDataForA(); //asynchronous request to the server
//async wait for the callback
processDataForA();
}
void functionB()
{
requestDataForB(); //asynchronous request to the server
//async wait for the callback
processDataForB();
}
void functionC()
{
requestDataForC(); //asynchronous request to the server
//async wait for the callback
processDataForC();
}
Now my question is that when the callback gives the data item, how to use it for subsequent processing. It cannot be done in callback as callback doesn't know who will use the data.
Thanks
Shiv
You implicitly have this information, you just need to track it. Lets say that object A calls functionA, you should make A implement a particular interface that accepts data related that is the response from calling requestA. Lets say this response is DataA, then the interface would be
class InterfaceADataHandler
{
public:
virtual void handle(DataA const&) = 0; // this is the method that will process the data..
};
class A : public InterfaceADataHandler
{
public:
void handle(DataA const&) {} // do something with data
// Now I want to be called back
void foo()
{
functionA(this); // call function A with this instance
}
};
void functionA(InterfaceADataHandler* pHandler)
{
// store this handler against request (say some id)
request..();
// wait for callback
// when you have callback, lookup the handler that requested the data, and call that handler
}
In most API's, you the developer would be providing the callback which will be invoked by the API with the data that has been retrieved. You can then store the data and use it at a later time or use it within the callback (assuming that you won't take very long to process and promise not to block for I/O).
The model would look more like:
void functionA()
{
requestDataForA(processDataForA); //asynchronous request to the server
}
void processDataForA(void *someData)
{
// process "someData"
}