I am trying to pass this pointer as an argument to my callback(), but it seems like the behaviour is not same as I expect.
I am trying to pass the caller object as my user_data (i.e. 2nd argument of callback() ), apparently it fails!
Within SaveSettings() method, if I type cast void*)obj to (SettingsGui*), and call foo(), it behaves as expected (so, I am able to pass a pointer to calling SettingsGui obj?), but when I try to access vector<string> Order (which is filled with string objects within SettingsGui::Show() method), it fails.
Is my assumption of "successfully passing a pointer to calling SettingsGui object" wrong? If so, why and how can I fix it?
// Gui for Application Settings
class SettingsGui {
vector<string> Order;
public:
const char foo() { return "Test"; }
void Show() {
...
Order.size(); /* it is 44 here */
...
// Save Button
Fl_Button *SaveButton = new Fl_Button(...);
SaveButton->callback(SaveSettings, this);
...
}
static void SaveSettings(Fl_Widget *w, void *d){
SettingsGui *T = (SettingsGui*)obj;
fl_alert(T->foo()); /* this works */
char buf[32];
fl_alert(itoa(T->Order.size(),buf,10)); /* return -1 */
}
};
// Main Application Window
class MainApp {
public:
void Show(){
...
...
Fl_Button *flButton_settings = new Fl_Button(...);
flButton_settings->callback(OpenSettingsGui);
}
static void OpenSettingsGui (Fl_Widget *w, void *d) {
SettingsGui p;
p.ReadSettings(...);
p.Show();
}
};
T->foo() works because it doesn't access anything within the class
T->Order.size() doesn't work because T is being cast to obj. It should be cast to d.
static void SaveSettings(Fl_Widget *w, void *d){
SettingsGui *T = (SettingsGui*)d;
Related
I have CPrinterDlg class which contains
// CPrinterDlg.h
public:
CEdit m_editRxFreq;
void print_SignalData(unsigned int freq, float wvlen);
// CPrinterDlg.cpp
void CPrinterDlg::print_SignalData(unsigned int freq, float wvlen)
{
m_editRxFreq.SetWindowTextW(L"ddd");
}
In order to access that function I did in MainFrm like this:
public:
CPrinterDlg m_PrinterDlg;
CPrinterDlg& getPrinterDlg() { return m_PrinterDlg; }
And from where I am calling print_SignalData(...) is CSMsg``` class
void CSockMsg::Send_SignalData(unsigned char* msg)
{
//..
CMainFrame* pMain = (CMainFrame*)AfxGetApp()->GetMainWnd();
pMain->getPrinterDlg().print_SignalData(freq, wvlen);
}
When I call print_SignalData(...) from one of the CPrinter function directly, it's working well. But, When I try to call it from CSMsg::Send_SignalData(unsigned char* msg) it's giving me Debug Assertion(...MFC\winocc.cpp Line: 242) from this point:m_editRxFreq.SetWindowTextW(L"ddd");.
And I see that m_editRxFreq is NULL.
So, how do you think why m_editRxFreq is getting be NULL? and how can I solve this problem??
Solved!
I was doing
public:
CPrinterDlg m_PrinterDlg;
CPrinterDlg& getPrinterDlg() { return m_PrinterDlg; }
in CMainFrm.h,
and actually Creating and Showing that dlg
CPrinterDlg dlg;
dlg.Create(...);
dlg.ShowWindow(...);
was in CxxView::OnInitialUpdate().
That's why when I called pMain->getPrinterDlg().print_SignalData(freq, wvlen); it was giving me NULL;
So in order to solve it,
I created CPrinterDlg dlg.Create(...) in CMainFrm class but not in CxxxView class.
Suppose I have a template class:
template<class T>
class Entity
{
public:
Entity(std::function<void(T*)> init, int idx) : index(idx)
{
init(data);
}
T* getData(){ return Data; }
private:
int index;
T* data;
};
And I create an instance of the class as so:
Entity<Button> myEnt([](Button* button){
button = new Button();
/* some complex, **unique**, initialization of button */
}, 1);
This will compile, but when I call getData() and attempt to use the pointer returned in some other function the program crashes. I assume its because there is an error where data doesn't get properly initialized, but I cant tell why!
fwiw I can get the program to run as desired if I change the Entity constructor to:
Entity(std::function<T*(void)> init, int idx) : index(idx)
{
data = init();
}
and then call it as so:
Entity<Button> myEnt([](){
Button* button = new Button();
/* some complex, **unique**, initialization of button */
return button;
}, 1);
But in my opinion that's an undesirable way of doing it, and the first method should work, im just missing something.
You are passing data to init() by value, which means the lambda is receiving a copy of data. So any value the lambda assigns to its input parameter will be assigned to the copy and not reflected back to data.
You need to pass data by reference instead, eg:
template<class T>
class Entity
{
public:
Entity(std::function<void(T*&)> init, int idx) : index(idx)
{
init(data);
}
T* getData(){ return data; }
private:
int index;
T* data;
};
Entity<Button> myEnt([](Button* &button){
button = new Button();
/* some complex, **unique**, initialization of button */
}, 1);
If you want to initialize the pointer member, you need a reference or pointer to the member pointer, not the value of the pointer.
template<class T>
class entity
{
public:
Entity(std::function<void(T**)> init, int idx) : index(idx)
{
init(&data);
}
T* getData(){ return data; }
Private:
int index;
T* data;
}
Use it like this:
Entity<Button> myEnt([](Button** button){
// you need a pointer to the pointer in order to initialize it
*button = new Button();
/* some complex, **unique**, initialization of button */
}, 1);
The Settings: I'm building an architecture that has parts in C and part in C++.
In my Architecture I have:
A data_io(C) which gets data sends it to a processor callback and outputs the processed data.
A data_processor(C) which takes care of processing data and changes on-demand.
A settings_manager(C++) which decides which processor to use.
The relationship is as follows:
The settings_manager object is instantiated, inside it initializes the data_processor with a default processor function, and then initializes the data_io sending to it a processing_callback_function (defined in the settings_manager, but internally referencing a data_processor function) which is then used to process the data when the data_io starts. (so, the data_io receives the processing_callback_function only once at initialization and does not care about what the callback does inside, it just generates data, calls the processing_callback_function and outputs processed data)
While the system is working, the settings_manager may decide to change the data_processor type of processing, so it changes the processing_callback_function to call a different data_processor function.(the data_io does not know about it and continues working)
Here is the basic implementation:
data_io.c:
typedef void (* ProcessorCallback_t)(float *, int);
ProcessorCallback_t processorCallback;
data_io_init(ProcessorCallback_t callback) {
processorCallback;
...init all other stuff like data pointer...
}
data_io_loop() {
bufSize = readData(&data);
processorCallback(&data, bufSize);
writeData(&data, bufSize);
}
data_procesor.c:
void data_processor_init() {
...initialization routine...
}
void data_processor_proc1(float *data, int bufSize) {
...data process...
}
void data_processor_proc2(float *data, int bufSize) {
...data process...
}
settings_manager.cpp:
void SettingsManager::start() {
data_processor_init();
this->processing_function = &data_processor_proc1;
//THIS IS MY QUESTION! HOW TO PASS THE processing_callback_function TO data_io_init
data_io_init(&SettingsManager::processing_callback_function);
... here starts a new thread to run loop below...
//while(this->condition) {
// data_io_loop();
//}
}
void SettingsManager::changeProcessorType(int processorType) {
switch(processorType) {
case 1:
this->processing_function = &data_processor_proc1;
break;
case 2:
this->processing_function = &data_processor_proc2;
break;
}
}
void SettingsManager::processing_callback_function(float *data, int buffer_size) {
this->processing_function(data, buffer_size);
}
My Questions:
1. How should I pass the processing_callback_function C++ member function to the data_io_init C function?
when I do the following:
data_io_init(&SettingsManager::processing_callback_function);
I get the following error:
"Incompatible pointer types 'ProcessorCallback_t' and 'void(Engine::*)(float*,int)'"
Well the error is obvious, the types are different as the second is a member function and is part of the instance of the object.
I've read that I should make the processing_callback_function static, but I'm not sure if it is the right approach.
What is the appropriate way to handle this kind of things, are there any patrons that might be useful to read, or coding strategies that may be related?
A non-static class method has a hidden this pointer that a free-standing function does not. So such, you can't pass a non-static class method where a free-standing function is expected.
The best solution in this situation is to allow the C++ code to pass a user-defined value to the C code, and then have the C code passes that value back to the C++ code. That way, the C++ code can pass around its this pointer. For example:
data_io.h:
typedef void (* ProcessorCallback_t)(float *, int, void *);
void data_io_init(ProcessorCallback_t callback, void *userdata);
void data_io_loop();
data_io.c:
ProcessorCallback_t processorCallback;
void *processorUserData;
void data_io_init(ProcessorCallback_t callback, void *userdata) {
processorCallback = callback;
processorUserData = userdata;
...init other stuff as needed ...
}
void data_io_loop() {
...
processorCallback(&data, bufSize, processorUserData);
...
}
Then SettingsManager can do this:
settings_manager.h:
typedef void (* ProcessorFunc_t)(float *, int);
class SettingsManager
{
private:
ProcessorFunc_t processing_function;
...
static void processing_callback_function(float *data, int buffer_size void *userdata);
public:
void start();
...
};
settings_manager.cpp:
#include "data_io.h"
void SettingsManager::start()
{
...
data_io_init(&SettingsManager::processing_callback_function, this);
...
}
void SettingsManager::processing_callback_function(float *data, int buffer_size void *userdata)
{
static_cast<SettingsManager*>(userdata)->processing_function(data, buffer_size);
}
Or this (as the above is technically undefined behavior, but it does work in most compilers. The below is more standards compliant):
settings_manager.h:
typedef void (* ProcessorFunc_t)(float *, int);
class SettingsManager
{
...
public:
ProcessorFunc_t processing_function;
void start();
...
};
settings_manager.cpp:
#include "data_io.h"
void processing_callback_function(float *data, int buffer_size void *userdata)
{
static_cast<SettingsManager*>(userdata)->processing_function(data, buffer_size);
}
void SettingsManager::start()
{
...
data_io_init(&processing_callback_function, this);
...
}
1) Write everything in C++. Use std::function as a callback. This is the best way to handle this. Do you really have a performance issue? Have you measured it? C++ is not that slow. Problems that you will have by mixing two lanuage styles will bring more problems.
2) Functions are the same in C and C++. You can always do the following:
class Cls {
public:
void callback() {}
};
void Cls_callback(void* ptr) {
reinterpret_cast<Cls*>(ptr)->callback();
}
And then pass that Cls_callback as the C callback.
3) You may make Cls_callback a static method of Cls and that way it will have access to private members of Cls:
class Cls {
public:
static void Cls_callback(void* ptr) {
Cls* self = reinterpret_cast<Cls*>(ptr);
self->i += 1;
}
private:
int i;
};
But keep in mind, that this actually is an UB. It will work, it is slightly less code than variant 2, but technically speaking, standard does not guarantee that this will work.
P.S. Yet again, don't mix styles. Use C++ everywhere.
I found several similar questions, but the solutions didn't suit my case.
In a C++ method, I call a C api, which takes a callback as one of its parameter.
class A
{
herr_t methodA(some parameters) {....}
void methodB(some parameters)
{
....
int status = CAPI(other parameters, callback, last parameter);
}
};
The prototype of CAPI is
herr_t CAPI( some parameters, H5L_iterate_t op, other parameters);
H5L_iterate_t is defined by
herr_t (*H5L_iterate_t)( hid_t g_id, const char *name,
const H5L_info_t *info, void *op_data)
methodA has the same signature as H5L_iterate_t.
In methodB,
status = CAPI(..., **(H5L_iterate_t )std::bind(&A::methodA, this,
std::placeholders::_1)**, ...);
The compile error I got was "Can't convert from ... to H5L_iterate_t". I'm wondering what's the right way to pass the non static member function as a callback.
Thanks in advance.
C APIs offering a callback almost always follow this pattern:
extern "C"
{
typedef void(*callback_function)(void* data);
typedef int handle_type;
void do_something_with_callback(handle_type, callback_function, void *data);
}
The idea being that whatever you pass as the data argument when do_something_with_callback is called, will be passed to the callback_function.
You can use this user data to pass a pointer to your c++ object's address, which you can then cast back to a pointer to your object type:
struct my_object
{
void initiate()
{
// call the C interface, passing our c-style callback function with
// a pointer to this class as the user data
do_something_with_callback(handle_, &callback_launch_function, this);
}
private:
static void callback_launch_function(void * data) {
// the data will always be a pointer to my_object -
// because that's what we passed.
auto self = reinterpret_cast<my_object*>(data);
self->handle_it();
}
// this is our c++style callback
void handle_it()
{
}
handle_type handle_;
};
So below is a basic idea of what I'm trying to do.
I have an external library that I would like to use in an existing project.
I cannot change anything in the external library or the main function in the existing project of course.
The problem I face is how to pass a callback function I make in my class to this external function as a pointer to function. At the same time, this callback function has to have access to members of the class so I cannot simply make it static. How can I do it?
Class ExternalClass //This I cannot mess with.
{
//somestuff
void ExternalFunc (void(* callback)(int, const void*), const void *);
}
Class MyClass
{
//somestuff
ExternalClass m_ExObj;
void Callback(int x, const void *p){
//dosomething
//How do I use this pointer ?
}
void MyFunc(){
m_ExObj.ExternalFunc(/*Some way to put MyClass::Callback() in here*/)
}
}
The callback you have shown does not allow a user-defined value to be passed to it (otherwise you could use that for passing around your object pointer). It expects a standalone non-class function, so you have two options:
1) if the callback only ever calls into a single object at one time, then you can store the object pointer in a global or static variable, and then use a standalone function (or static class method) as the callback and have it use the global/static pointer to call your class method:
class MyClass
{
//somestuff
ExternalClass m_ExObj;
void Callback(int x)
{
//dosomething
}
static MyClass* objForCallback;
static void exObjCallback(int x) { objForCallback->Callback(x); }
void MyFunc()
{
objForCallback = this;
m_ExObj.ExternalFunc(&exObjCallback);
}
};
2) if you need to have callbacks for multiple objects at a time, you will have to wrap your class method inside a per-object thunk, where each thunk knows which object to call into, and then you use the thunks as callbacks. This is a more advanced technique, requiring an understanding of x86/x64 assembly and calling conventions, as you have to allocate memory dynamically and populate it with assembly instructions for each thunk to execute at runtime. For example, at least on Windows 32bit:
#pragma pack(push, 1)
struct MyThunk
{
unsigned char PopEAX_1; // POP the caller's return address off the stack
unsigned char PushThis; // PUSH the object 'this' pointer on to the stack
void *ThisValue;
unsigned char PushEAX_1; // PUSH the caller's return address back on to the stack
unsigned char Call; // CALL the callback function
__int32 CallAddr;
unsigned char PopEAX_2; // POP the caller's return address off the stack
unsigned char AddESP[3]; // Remove the object 'this' pointer from the stack
unsigned char PushEAX_2; // PUSH the caller's return address back on to the stack
unsigned char Return; // return to the caller
};
#pragma pack(pop)
typedef void (*CallbackType)(int);
class MyClass
{
CallbackType exObjCallback;
MyClass()
{
MyThunk *thunk = (MyThunk*) VirtualAlloc(NULL, sizeof(MyThunk), MEM_COMMIT, PAGE_READWRITE);
if (thunk)
{
thunk->PopEAX_1 = 0x58;
thunk->PushThis = 0x68;
thunk->ThisValue = this;
thunk->PushEAX_1 = 0x50;
thunk->Call = 0xE8;
thunk->CallAddr = reinterpret_cast<__int32>(Callback) - (reinterpret_cast<__int32>(&thunk->Call) + 5);
thunk->PopEAX_2 = 0x58;
thunk->AddESP[0] = 0x83;
thunk->AddESP[1] = 0xC4;
thunk->AddESP[2] = 0x04;
thunk->PushEAX_2 = 0x50;
thunk->Return = 0xC3;
DWORD dwOldProtect;
VirtualProtect(thunk, sizeof(MyThunk), PAGE_EXECUTE, &dwOldProtect);
FlushInstructionCache(GetCurrentProcess(), thunk, sizeof(MyThunk));
exObjCallback = (CallbackType) thunk;
}
}
~MyClass()
{
if (exObjCallback)
VirtualFree(exObjCallback, 0, MEM_RELEASE);
}
//somestuff
ExternalClass m_ExObj;
// NOTE: pCtx is the return address inside of ExternalFunc()
// where the callback is being called from. Because the
// callback is using the __cdecl calling convention, the
// thunk needs to remember this value and restore it after
// Callback() exits. Passing it as a parameter to Callback()
// is a quick-n-dirty way for the thunk to do that...
static void __cdecl Callback(void *pCtx, MyClass *pThis, int x)
{
//dosomething with pThis
}
void MyFunc()
{
if (exObjCallback)
m_ExObj.ExternalFunc(exObjCallback, ...);
}
};
When ExternalFunc() calls its callback, it will be calling the thunk, executing the instructions it contains. The thunk above is injecting the object's this pointer into the call stack as a parameter for Callback() as if ExternalFunc() had called it directly.
Update: in lieu of new information about the callback actually accepting a user-defined value, that greatly simplifies things:
class MyClass
{
//somestuff
ExternalClass m_ExObj;
static void Callback(int x, const void *p) {
MyClass *pThis = (MyClass*) p;
//dosomething with pThis
}
void MyFunc() {
m_ExObj.ExternalFunc(&Callback, this);
}
};