Pass a function pointer to a method of another class - c++

I'm working on my first C++ project. I have 2 classes: 1 for the interaction with the sqlite db, the other one for the qt main window. In the main I create a new window. In the window constructor I would like to load the content of the db and display it in a QtWidget.
So if I understand well sqlite callback function will be called for each row that the sqlite3_exec returns. I made a select_all function in the database class which takes a callback function as an argument so I'll be able to do use the same sql function to display/use the data in different ways.
#include <cstdio>
#include <iostream>
#include <QtCore>
#include <QtGui>
#include <QtWidgets>
#include <qmainwindow.h>
#include <qstandarditemmodel.h>
#include <sqlite3.h>
#include <string>
using namespace std;
class Database {
public:
sqlite3* db;
Database() {db = create_or_open_database();}
sqlite3* create_or_open_database()
{
sqlite3 *db = NULL;
const char *query;
int ret = 0;
char *errorMsg = 0;
ret = sqlite3_open("expense.db", &db);
query = "CREATE TABLE IF NOT EXISTS EXPENSES(NAME TEXT KEY NOT NULL, AMOUNT INT NOT NULL, TAG TEXT, SUBTAG TEXT, DATE CHAR(10) NOT NULL);";
ret = sqlite3_exec(db, query, callback, 0, &errorMsg);
return db;
}
void select_all(int (*f)(void*, int, char**, char**)){
int ret = 0;
char *errorMsg = 0;
const char *query = "SELECT * FROM EXPENSES";
ret = sqlite3_exec(db, query, (*f), 0, &errorMsg);
}
};
class MainWindow
{
public:
QWidget window;
Database expenses;
QTreeView *navigateView = new QTreeView;
QTreeView *expensesList = new QTreeView;
QPushButton *newButton = new QPushButton;
QVBoxLayout *mainVLayout = new QVBoxLayout;
QHBoxLayout *listHLayout = new QHBoxLayout;
QStandardItemModel *expensesModel = new QStandardItemModel;
MainWindow()
{
QSizePolicy navigateSize(QSizePolicy::Preferred, QSizePolicy::Preferred);
QSizePolicy expenseListSize(QSizePolicy::Preferred, QSizePolicy::Preferred);
navigateSize.setHorizontalStretch(1);
navigateView->setSizePolicy(navigateSize);
expenseListSize.setHorizontalStretch(2);
expensesList->setSizePolicy(expenseListSize);
newButton->setText("New");
listHLayout->addWidget(navigateView);
listHLayout->addWidget(expensesList);
mainVLayout->addLayout(listHLayout);
mainVLayout->addWidget(newButton);
window.setLayout(mainVLayout);
// int (MainWindow::*foo)(void*, int, char**, char**) = &MainWindow::display_expenses_in_list;
// expenses.select_all(foo);
expenses.select_all(this->display_expenses_in_list);
}
int display_expenses_in_list(void *NotUsed, int argc, char **argv, char **azColName)
{
QStringList list = {"Name", "Amount (€)", "Tag", "Subtag", "Date"};
this->expensesModel->setVerticalHeaderLabels(list);
// here I'll create items and add them to the QTreeView
return 0;
}
};
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
MainWindow ui;
ui.window.show();
return app.exec();
}
With this code I get reference to a non-static member function must be called [bound_member_function]
If googled it and tried, I guess, to create a function pointer foo that point to the callback function (the lines that are currently commented). I get this : Cannot initialize a parameter of type 'int (*)(void *, int, char **, char **)' with an lvalue of type 'int (MainWindow::*)(void *, int, char **, char **)' [init_conversion_failed]
If I make display_expenses_in_list static then I can't edit the expensesModel...

The key here is that void* argument to sqlite3_exec. You now pass 0, but you need to pass this instead.
You can now make display_expenses_in_list static. That NotUsed parameter then becomes used. You just need to cast it back to MainWindow* and use it instead of this.

The problem:
The problem is your display_expenses_in_list(...) function is a class member function. Therefore your need to use a pointer to a member function rather than a pointer to a function, because it must always be called on an instance of the class it's a member of - however the sqlite library will only take a void* function pointer.
Check out this article: https://isocpp.org/wiki/faq/pointers-to-members
The fix:
Modern C++ to the rescue here. Wrap up your whole class member function call up in a lambda with the class instance in scope, then pass a pointer to this new, anonymous function as the callback.
Check this stackoverflow answer out showing how to do it (copied below): https://stackoverflow.com/a/31461997/410072
An example (copied from the linked answer):
if (sqlite3_exec(this->db, this->SQL_SELECT_READINGS_QUERY,
+[](void* instance, int x, char** y, char** z) {
return static_cast<dataSend_task*>(instance)->callback(x, y, z);
},
this,
&err))
{
/* whatever */
}

Related

Passing QWidget* as function parameter doesn't behave as expected [duplicate]

This question already has answers here:
Can I modify the target of a pointer passed as parameter?
(3 answers)
Closed 2 years ago.
I want to pass QWidget pointer to a function to get some widget back as a result of function actions. But the value of this pointer leaves the same as befoere.
Next code
#include <QApplication>
#include <QWidget>
#include <QDebug>
class Test
{
public:
QWidget *_widget;
Test()
{
_widget = new QWidget;
}
void test_pointer(QWidget *w) const
{
w = _widget;
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget *w = nullptr;
Test t;
t.test_pointer(w);
qDebug() << w;
return app.exec();
}
outputs
QWidget(0x0)
What's wrong?
You pass the pointer as copy, which means the outside pointer is not modified by the inside assignment. Instead you have to pass a pointer or a reference to your QWidget*.

TeamSpeak SDK in Qt

I'm trying to use the TeamSpeak SDK for a personal project in Qt, when I use this code in the main it works fine
It compiles without problem. The problem is when I use it in Qt Mainwindow:
Mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <teamspeak/public_definitions.h>
#include <teamspeak/public_errors.h>
#include <teamspeak/serverlib_publicdefinitions.h>
#include <teamspeak/serverlib.h>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
void onClientConnected(uint64 serverID, anyID clientID, uint64 channelID, unsigned int* removeClientError);
ServerLibFunctions funcs; // it's a struct that have pointer fucntions
};
#endif // MAINWINDOW_H
Mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
funcs.onClientConnected = onClientConnected; // error here
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::onClientConnected(uint64 serverID, anyID clientID, uint64 channelID, unsigned int* removeClientError) {
char* clientName;
unsigned int error;
/* Query client nickname */
if ((error = ts3server_getClientVariableAsString(serverID, clientID, CLIENT_NICKNAME, &clientName)) != ERROR_ok) {
char* errormsg;
if (ts3server_getGlobalErrorMessage(error, &errormsg) == ERROR_ok) {
printf("Error querying client nickname: %s\n", errormsg);
ts3server_freeMemory(errormsg);
}
return;
}
printf("Client '%s' joined channel %llu on virtual server %llu\n", clientName, (unsigned long long) channelID, (unsigned long long)serverID);
/* Example: Kick clients with nickname "BlockMe from server */
if (!strcmp(clientName, "BlockMe")) {
printf("Blocking bad client!\n");
*removeClientError = ERROR_client_not_logged_in; /* Give a reason */
}
}
I've commented on the line I got the error in Mainwindow.cpp
and the error:
cannot convert 'MainWindow::onClientConnected' from type 'void (MainWindow::)(uint64, anyID, uint64, unsigned int*) {aka void (MainWindow::)(long long unsigned int, short unsigned int, long long unsigned int, unsigned int*)}' to type 'void ()(uint64, anyID, uint64, unsigned int) {aka void ()(long long unsigned int, short unsigned int, long long unsigned int, unsigned int)}'
funcs.onClientConnected = onClientConnected;
^
I am using Windows 10 Mingw compiler Qt 5.6.1
how can i use this call back fucntion in oop c++
I solve my problem to use TeamSpeak in Qt I initialize the server in the main.cpp and assign all call back functions in the struct and now I can use any function of the server in the main window for example if I want to show the channels in a text edit i use the function of it in any c++ class or Qt Dialog and I can call it without problems
the code of the main.cpp
// put the fucntion of the call back here
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
char *version;
short abort = 0;
uint64 serverID;
unsigned int error;
int unknownInput = 0;
uint64* ids;
int i;
struct ServerLibFunctions funcs;
/* Initialize all callbacks with NULL */
memset(&funcs, 0, sizeof(struct ServerLibFunctions));
funcs.onClientConnected = onClientConnected;
funcs.onClientDisconnected = onClientDisconnected;
funcs.onClientMoved = onClientMoved;
funcs.onChannelCreated = onChannelCreated;
funcs.onChannelEdited = onChannelEdited;
funcs.onChannelDeleted = onChannelDeleted;
funcs.onServerTextMessageEvent = onServerTextMessageEvent;
funcs.onChannelTextMessageEvent = onChannelTextMessageEvent;
funcs.onUserLoggingMessageEvent = onUserLoggingMessageEvent;
funcs.onClientStartTalkingEvent = onClientStartTalkingEvent;
funcs.onClientStopTalkingEvent = onClientStopTalkingEvent;
funcs.onAccountingErrorEvent = onAccountingErrorEvent;
funcs.onCustomPacketEncryptEvent = nullptr;
funcs.onCustomPacketDecryptEvent = nullptr;
if((error = ts3server_initServerLib(&funcs, LogType_FILE | LogType_CONSOLE | LogType_USERLOGGING, NULL)) != ERROR_ok) {
char* errormsg;
if(ts3server_getGlobalErrorMessage(error, &errormsg) == ERROR_ok) {
printf("Error initialzing serverlib: %s\n", errormsg);
ts3server_freeMemory(errormsg);
}
return 1;
}
MainWindow w;
w.show();
return a.exec();
// use any function to edit server in any c++ class as show chan add chancel and so on
}
use all function to edit the server in any c++ class it will work and i think we don't need to initialize the server more than once in main and we don't need to but it in class and if I want to make a VoIP using Qt GUI we need only the server edit function if there's a better answer please post it Thanks
Edit
another solution is to initialize the struct with the call back functions in main and pass it in Mainwindow or any c++ class in the constructor and use it to initialize server lib of TeamSpeak
Your issue can be simulated with below simple code.
Based on my understanding the function you are trying to assign is a class specific member. So the compiler considers it as a signature mismatch when you are trying to assign.
You may need to write the required functionality in a non class member and then assign. (unless there is a way to allow this assignment).
Make the structure with function inputs as a friend of your functional class as shown below.
#include <iostream>
// common namespace
using namespace std;
//Structure with function pointers.
struct funcPtrStruct
{
public:
void (*func)(int a, float b);
};
//The non member function that address your functionality
void testFuncOne(int a ,float b)
{
//Do something
}
//Class implementation
class Test
{
public:
Test()
{
funcPtrStruct funPtrSt;
//func = &testFunc; //Here the error is shown " a value of type .....can not convert......"
funPtrSt.func = &testFuncOne; //This is working but it is not a class memeber.
}
private:
friend struct funcPtrStruct; //Make the structure of function pointers as your friend.
};
int main() {
return 0;
}

QDataStream is becoming Readonly

I have two classes named IPCBase and DispatchData. Now I want to pass QDataStrean Object drom IPCBase to DispatchData. First I tried to send it directly using Connect Statement. But it is giving error like QDataStream object is not registered in QRegisterMatatype.
edit :: I have refered this link as well
When, where and why use namespace when registering custom types for Qt
So I have done something like
typedef QDataStream* myDataStrem;
Q_DECLARE_METATYPE(myDataStrem)
and then connect statement in another class(DispatchData)
connect(mpThrIPCReceiver, SIGNAL(dispatchReadData(const int&, myDataStrem)),
this, SLOT(onIPCDataReceived(const int&, myDataStrem)));
onIPCDataReceived Slot
void DispatchData::onIPCDataReceived(const int& msgType, myDataStrem dataReceived)
{
// dataReceived >> str1; Here it is giving error
// qDebug()<<"is"<<str1;
MemberFuncPointer f = mIPCCommandMapper.value(msgType);
(this->*f)(*dataReceived);
//This is function pointer which will rout it to respective function depending on the Message type.
and then it will come here
void DispatchData::onStartCountingCycle(QDataStream &dataReceived)
{
int data = 0;
dataReceived >> data; //Here it is crashing
//Giving error like
//pure virtual method called
//terminate called without an active exception
// I have debugged it and here dataReceived is becoming Readonly.
}
It seems like you're passing around a dangling pointer: the data stream seems to not exist anymore by the time the receiving thread gets to it. Even if you extended its lifetime in the source object, it's a bad idea to pass a raw pointer through signal-slot connections. If the source class might vanish while the receiver thread has a pending slot call, you'll still be using a dangling pointer at the receiver. You'd be best served by passing around a QSharedPointer or std::shared_ptr.
The following works, you can of course use any type in the shared pointer.
#include <QtCore>
#include <cstdio>
struct Class : public QObject {
Q_SIGNAL void source(QSharedPointer<QTextStream>);
Q_SLOT void destination(QSharedPointer<QTextStream> stream) {
*stream << "Hello" << endl;
}
Q_OBJECT
};
Q_DECLARE_METATYPE(QSharedPointer<QTextStream>)
int main(int argc, char ** argv) {
QCoreApplication app{argc, argv};
Class c;
c.connect(&c, &Class::source, &c, &Class::destination, Qt::QueuedConnection);
auto out = QSharedPointer<QTextStream>(new QTextStream(stdout));
emit c.source(out);
QMetaObject::invokeMethod(&app, "quit", Qt::QueuedConnection);
*out << "About to exec" << endl;
return app.exec();
}
#include "main.moc"
Output:
About to exec
Hello
On modern Qt (5.6 at least), you don't need to call qRegisterMetatype in this case.
The same using std::shared_ptr:
// https://github.com/KubaO/stackoverflown/tree/master/questions/datastream-pass-37850584
#include <QtCore>
#include <cstdio>
#include <memory>
struct Class : public QObject {
Q_SIGNAL void source(std::shared_ptr<QTextStream>);
Q_SLOT void destination(std::shared_ptr<QTextStream> stream) {
*stream << "Hello" << endl;
}
Q_OBJECT
};
Q_DECLARE_METATYPE(std::shared_ptr<QTextStream>)
int main(int argc, char ** argv) {
QCoreApplication app{argc, argv};
Class c;
c.connect(&c, &Class::source, &c, &Class::destination, Qt::QueuedConnection);
auto out = std::make_shared<QTextStream>(stdout);
emit c.source(out);
QMetaObject::invokeMethod(&app, "quit", Qt::QueuedConnection);
*out << "About to exec" << endl;
return app.exec();
}
#include "main.moc"

Function call missing argument list to create pointer

I tried to connect my app to OpenViBE through VRPN server. My app works well until I try to add code to connect my app to VRPN server.
My code looks like this:
MainWindow.c code:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtUiTools/QUiLoader>
#include <QFile>
#include <QMessageBox>
#include <QFileDialog>
#include <iostream>
using namespace std;
#include "vrpn_Analog.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
currentImage = 0;
labelSize = ui->label_2->size();
createActions();
openFileDialog();
}
void MainWindow::checkChannels()
{
vrpn_Analog_Remote *vrpnAnalog = new vrpn_Analog_Remote("Mouse0#localhost");
vrpnAnalog->register_change_handler( 0, handle_analog );
}
void VRPN_CALLBACK MainWindow::handle_analog( void* userData, const vrpn_ANALOGCB a )
{
int nbChannels = a.num_channel;
cout << "Analog : ";
for( int i=0; i < a.num_channel; i++ )
{
cout << a.channel[i] << " ";
}
cout << endl;
}
MainWindow.h code:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QFileInfoList>
#include "vrpn_Analog.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
void resizeEvent(QResizeEvent *);
private slots:
void openFileDialog();
private:
void checkChannels();
void VRPN_CALLBACK handle_analog( void* userData, const vrpn_ANALOGCB a );
};
#endif // MAINWINDOW_H
With this code, when I try to run my app I get:
error: C3867: 'MainWindow::handle_analog': function call missing argument list; use '&MainWindow::handle_analog' to create a pointer to member
I try to edit code by error advice, but I get another error:
error: C2664: 'vrpn_Analog_Remote::register_change_handler' : cannot convert parameter 2 from 'void (__stdcall MainWindow::* )(void *,const vrpn_ANALOGCB)' to 'vrpn_ANALOGCHANGEHANDLER'
There is no context in which this conversion is possible
I search around, but I don't find any usable solution.
Methods checkChannels and handle_analog I "copy" from this code, where all works fine:
#include <QtCore/QCoreApplication>
#include <iostream>
#include "vrpn_Analog.h"
void VRPN_CALLBACK vrpn_analog_callback(void* user_data, vrpn_ANALOGCB analog)
{
for (int i = 0; i < analog.num_channel; i++)
{
if (analog.channel[i] > 0)
{
std::cout << "Analog Channel : " << i << " / Analog Value : " << analog.channel[i] << std::endl;
}
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
/* flag used to stop the program execution */
bool running = true;
/* VRPN Analog object */
vrpn_Analog_Remote* VRPNAnalog;
/* Binding of the VRPN Analog to a callback */
VRPNAnalog = new vrpn_Analog_Remote("openvibe_vrpn_analog#localhost");
VRPNAnalog->register_change_handler(NULL, vrpn_analog_callback);
/* The main loop of the program, each VRPN object must be called in order to process data */
while (running)
{
VRPNAnalog->mainloop();
}
return 0;
return a.exec();
}
Where I'm doing mistake? Thanks for all replies.
I had a similar error in Visual Studio: "function call missing argument list; use '&className::functionName' to create a pointer to member"..
I was just missing the parenthesis when calling the getter, so className.get_variable_a()
The error message tells you that the argument you provided does not match vrpn_ANALOGCHANGEHANDLER. You didn't show the definition of that. I checked online and it suggested
typedef void (*vrpn_ANALOGCHANGEHANDLER)(void *userdata, const vrpn_ANALOGCB info);
so I'm going with that.
Your code attempts to pass a pointer-to-member-function, which cannot be converted to a pointer-to-function. This is because a pointer-to-member-function can only be called on an object, so it wouldn't know what object to use.
If you look at the code you are "copying off", you will see that vrpn_analog_callback is a free function. However in your code it is a member function. You need to change your code so that the callback is a free function (or a static member function).
If your intent is that the callback should call the member function on the same MainWindow object that you are registering the handler on, then do this:
// In MainWindow's class definition, add this:
static void VRPN_CALLBACK cb_handle_analog( void* userData, const vrpn_ANALOGCB a )
{
static_cast<MainWindow *>(userData)->handle_analog(NULL, a);
}
// In checkChannels()
vrpnAnalog->register_change_handler( this, cb_handle_analog );
You cannot directly call a non-static class method using this callback. This is because the method is expecting to be called with the class this pointer.
If you don't need any data from your class, then just make the method static. If you do need data from the class, you can make a static "stub" that takes the class pointer in the userData parameter and then calls the original method. Something like:
Declaration:
static void VRPN_CALLBACK handle_analog_stub( void* userData, const vrpn_ANALOGCB a );
Definition
void VRPN_CALLBACK MainWindow::handle_analog_stub( void* userData, const vrpn_ANALOGCB a )
{
MainWindow *mainWindow = static_cast<MainWindow*>(userData);
mainWindow->handle_analog(NULL, a);
}
Then when you call the function use:
vrpnAnalog->register_change_handler( this, handle_analog_stub );
(Updated to static_cast to pointer, thanks rpavlik)

How can I use boost::bind to bind a class member function?

#include <QtCore/QCoreApplication>
#include <boost/bind.hpp>
#include <boost/function.hpp>
class button
{
public:
boost::function<void()> onClick;
boost::function<void(int ,double )> onClick2;
};
class player
{
public:
void play(int i,double o){}
void stop(){}
};
button playButton, stopButton;
player thePlayer;
void connect()
{
//error C2298: 'return' : illegal operation on pointer to member function expression
playButton.onClick2 = boost::bind(&player::play, &thePlayer);
stopButton.onClick = boost::bind(&player::stop, &thePlayer);
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
connect();
return a.exec();
}
boost::bind(&player::play, &thePlayer)
You need to use placeholders for the two arguments:
boost::bind(&player::play, &thePlayer, _1, _2)
The placeholders allow you to say "I'm only binding certain arguments; other arguments will be provided later."
And if you want create portable code - specify namespace of placeholders directly:
boost::bind( &player::play, &thePlayer, ::_1, ::_2 ); // Placeholders of boost::bind are placed in global namespace.