TeamSpeak SDK in Qt - c++

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;
}

Related

Functionpointer based syntax for QMetaObject invokeMethod

I'm working on a simple wrapper for a IPC lib we are using.
I want to convert the events from this lib to calls on Qt slots.
Right now i have something like this:
void Caller::registerCallback(int id, QObject* reciever, const char* member)
{
_callbackMap[id] = std::make_pair(reciever, QString(member));
}
bool Caller::call(const SomeData data)
{
auto reciever = _callbackMap.value(data.id);
return QMetaObject::invokeMethod(reciever.first, reciever.second.toLocal8Bit(), Qt::QueuedConnection,
QGenericReturnArgument(),
Q_ARG(SomeData, data));
}
void Receiver::someCallback(SomeData data)
{
qDebug() << data.str;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Caller caller;
Receiver reciever;
caller.registerCallback(1, &reciever, "someCallback");
caller.call(SomeData({ "Hi", 1 }));
return a.exec();
}
struct SomeData {
QString str;
int id;
}; Q_DECLARE_METATYPE(SomeData);
This works quite well. But I don't like to register the callbacks as strings. I would prefer a compile time checking with a syntax like this:
caller.registerCallback(1, &reciever, &Reciever::someCallback);
I am aware of this implementation.
The slots I want to register always have exactly one argument and no return value.
I already found this request what could solve my problem but unfortunately this was never implemented.
Also this question doesn't help me as I'm not able to patch the moc we are using.
So is this really not possible with all the meta magic Qt is using?
EDIT:
I found a solution that works also when the Caller dose not know about the Receiver (what is actually what I need):
//Caller.h
class Caller : public QObject
{
Q_OBJECT
public:
Caller(QObject *parent = nullptr);
~Caller();
//void registerCallback(int id, QObject* reciever, const char *member);
template < class R, typename Func >
void inline registerCallback(int id, R reciever, Func callback)
{
using std::placeholders::_1;
registerCallbackImpl(id, reciever, std::bind(callback, reciever, _1));
};
bool call(const SomeData);
private:
QMap<int, std::pair<QObject *, std::function<void(SomeData)>> > _callbackMap;
void registerCallbackImpl(int id, QObject* reciever, std::function<void(SomeData)> callback);
};
//Caller.cpp
void Caller::registerCallbackImpl(int id, QObject* reciever, std::function<void(SomeData)> callback)
{
_callbackMap[id] = std::make_pair(reciever, callback);
}
bool Caller::call(const SomeData data)
{
auto reciever = _callbackMap.value(data.id).first;
auto fn = _callbackMap.value(data.id).second;
QMetaObject::invokeMethod(reciever, [reciever, fn, data]() {
std::invoke(fn, data);
fn(data);
}, Qt::QueuedConnection);
return true;
}
//main.cpp
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Caller caller;
Receiver reciever;
using std::placeholders::_1;
caller.registerCallback(2, &reciever, &Receiver::someCallback);
caller.call(SomeData({ "Hi2", 2 }));
return a.exec();
}
This soulution relies upon std::invoke and lambda.
Variant 1: use std::invoke directly instead of QMetaObject::invoke
Variant 2: use std::invoke inside a lambda, which is passed to QMetaObject::invoke
Variant 3: use MACRO instead of std::invoke in variant 2.
If you use QMetaObject::invoke you've got an option to choose connection type - Direct or Queued. In variant 1 the call is invoked immediately like in direct connection.
receiver.h
#ifndef RECEIVER_H
#define RECEIVER_H
#include <QObject>
#include <QDebug>
struct SomeData {
QString str;
int id;
};
//Q_DECLARE_METATYPE(SomeData);
class Receiver : public QObject
{
Q_OBJECT
public:
explicit Receiver(QObject *parent = nullptr) : QObject(parent) {}
void doSmth(SomeData data) {
qDebug() << data.str;
}
signals:
};
#endif // RECEIVER_H
caller.h
#ifndef CALLER_H
#define CALLER_H
#include <QObject>
#include <QMap>
#include <utility>
#include <map>
#include "receiver.h"
#define CALL_MEMBER_FN(object,ptrToMember) ((object)->*(ptrToMember))
typedef void (Receiver::*callback)(SomeData);
class Caller : public QObject
{
Q_OBJECT
public:
explicit Caller(QObject *parent = nullptr) : QObject(parent) { }
void registerCallback(int id, Receiver* receiver, callback c)
{
auto pair = std::make_pair(receiver, c);
_callbackMap.emplace(id, pair);
}
bool call(const SomeData data)
{
auto &receiver = _callbackMap.at(data.id);
return QMetaObject::invokeMethod(receiver.first, [data, receiver] () {
// method 1
std::invoke(receiver.second, receiver.first, data);
// method 2 (better not to use a MACRO)
CALL_MEMBER_FN(receiver.first, receiver.second)(data);
}, Qt::QueuedConnection);
}
bool call_invoke(const SomeData data)
{
auto &receiver = _callbackMap.at(data.id);
std::invoke(receiver.second, receiver.first, data);
return true;
}
signals:
private:
std::map<int,std::pair<Receiver*,callback>> _callbackMap;
};
#endif // CALLER_H
main.cpp
#include <QCoreApplication>
#include "receiver.h"
#include "caller.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Caller caller;
Receiver reciever;
caller.registerCallback(1, &reciever, &Receiver::doSmth);
caller.registerCallback(2, &reciever, &Receiver::doSmth);
caller.call(SomeData({ "Hi", 1 }));
caller.call_invoke(SomeData({ "Hi2", 2 }));
return a.exec();
}
An alternative approach might be to use a suitable std::function to capture the callback and then make use of QTimer::singleShot with a zero timeout to invoke the callback in the correct context.
struct SomeData {
QString str;
int id;
};
class Caller {
public:
using task = std::function<void(SomeData)>;
void registerCallback (int id, QObject *receiver, task t)
{
_callbackMap[id] = std::make_pair(receiver, t);
}
bool call (SomeData data)
{
auto receiver = _callbackMap.value(data.id);
QTimer::singleShot(0, receiver.first, [=](){ receiver.second(data); });
return true;
}
private:
QMap<int, std::pair<QObject *, task>> _callbackMap;
};
class Receiver: public QObject {
public:
void someCallback (SomeData data)
{
qDebug() << data.str;
}
};
Then use as...
Caller caller;
Receiver receiver;
caller.registerCallback(1, &receiver, [&](SomeData d){ receiver.someCallback(d); });
caller.call(SomeData({ "Hi", 1 }));

Pass a function pointer to a method of another class

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 */
}

How to convert enum to QString?

I am trying to use the Qt reflection for converting enum to QString.
Here is the part of code:
class ModelApple
{
Q_GADGET
Q_ENUMS(AppleType)
public:
enum AppleType {
Big,
Small
}
}
And here is i trying to do:
convertEnumToQString(ModelApple::Big)
Return "Big"
Is this possible?
If you have any idea about convertEnumToQString, please share it
You need to use Q_ENUM macro, which registers an enum type with the meta-object system.
enum AppleType {
Big,
Small
};
Q_ENUM(AppleType)
And now you can use the QMetaEnum class to access meta-data about an enumerator.
QMetaEnum metaEnum = QMetaEnum::fromType<ModelApple::AppleType>();
qDebug() << metaEnum.valueToKey(ModelApple::Big);
Here is a generic template for such utility:
template<typename QEnum>
std::string QtEnumToString (const QEnum value)
{
return std::string(QMetaEnum::fromType<QEnum>().valueToKey(value));
}
Much more elegant way found (Qt 5.9), just one single line, with the help of mighty QVariant.
turns enum into string:
QString theBig = QVariant::fromValue(ModelApple::Big).toString();
Perhaps you don't need QMetaEnum anymore.
Sample code here:
ModelApple (no need to claim Q_DECLARE_METATYE)
class ModelApple : public QObject
{
Q_OBJECT
public:
enum AppleType {
Big,
Small
};
Q_ENUM(AppleType)
explicit ModelApple(QObject *parent = nullptr);
};
And I create a widget application, calling QVaraint function there :
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <modelapple.h>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QString s = QVariant::fromValue(ModelApple::Big).toString();
qDebug() << s;
}
MainWindow::~MainWindow()
{
delete ui;
}
You can see that i try to output the string on console , which really did:
And sorry for reverse casting , i tried successfully in some project , but some how this time i met compiling error. So i decide to remove it from my answer.
The following should get you going:
QString convertEnumToQString(ModelApple::AppleType type) {
const QMetaObject metaObject = ModelApple::staticMetaObject;
int enumIndex = metaObject.indexOfEnumerator("AppleType");
if(enumIndex == -1) {
/* The enum does not contain the specified enum */
return "";
}
QMetaEnum en = metaObject.enumerator(enumIndex);
return QString(en.valueToKey(type));
}
For the global Enum declaring use this in any header file:
namespace YourNamespace {
Q_NAMESPACE
enum YourEnum: int {
EnumValue1,
EnumValue2
};
Q_ENUM_NS(YourEnum)
}
and this where you want to get Enum description:
QMetaEnum metaEnum = QMetaEnum::fromType<YourEnum>();
qDebug() << "Enum description: " << metaEnum.name() << "::" << metaEnum.valueToKey(YourEnum::EnumValue2);
How about:
QString convertEnumToQString(ModelApple::AppleType type)
{
const QMetaObject &mo = ModelApple::staticMetaObject;
int index = mo.indexOfEnumerator("AppleType");
QMetaEnum metaEnum = mo.enumerator(index);
return metaEnum.valueToKey(type);
}
UPDATED: For Qt 5.5, see this answer
I faced the same problem and this is how i solved it. This is especially for Qt 4.8
QString string = enumToString(ModelApple::Big);
QString ModelApple::enumToString(AppleType apple)
{
int index = metaObject()->indexOfEnumerator("AppleType");
QMetaEnum metaEnum = metaObject()->enumerator(index);
return metaEnum.valueToKey(apple);
}

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)

accessing a static variable in C++

I'm using Qt Creator to try and create a basic calculator app. I was trying to test out the first few methods and had to write one in order to make the rest of the coding easier, however, that method isn't compiling. I'm trying to access a static variable that holds the current value of the Calculator screen, but it keeps giving me:
C:\Users\****\Documents\Qt Projects\SimpleCalculator\calculator.cpp:15: error: C2248: 'Calculator::currVal' : cannot access private member declared in class 'Calculator'
Here is the Calculator.cpp
#include "calculator.h"
#include <QLCDNumber>
Calculator::Calculator(QWidget *parent) :
QWidget(parent), ui(new Ui::Calculator)
{
ans = 0;
currVal = 0;
setupUi(this);
}
//problem method
QString getNewVal(qint64 nextDig)
{
//--------------------------------------------
long long int val = Calculator::currVal;//this is where I am trying to access the variable
//--------------------------------------------
if(nextDig==0)
{
if(val > 0)
{
QString str = QString::number(val);
str.append("0");
return str;
}
else
{
return "0";
}
}
else if(nextDig==1)
{
QString str = QString::number(val);
str.append("1");
return str;
}
return NULL;
}
void Calculator::on_Zero_clicked()
{
ui->Display->display(getNewVal(0));
currVal = ui->Display->intValue();
}
void Calculator::on_One_clicked()
{
}
Here is the header file:
#ifndef CALCULATOR_H
#define CALCULATOR_H
#include "ui_calculator.h"
class Calculator : public QWidget, private Ui::Calculator
{
Q_OBJECT
public:
Calculator(QWidget *parent = 0);
private slots:
void on_Zero_clicked();
void on_One_clicked();
private:
Ui::Calculator *ui;
QString getNewVal(quint64);
static long long int ans;
static long long int currVal;
};
long long int Calculator::ans = 0;
long long int Calculator::currVal = 0;
#endif
// CALCULATOR_H
Calculator::currVal;//this is where I am trying to access the variable
Won't work because the value is declared private (as indicated by the warning) in your header:
private:
Ui::Calculator *ui;
QString getNewVal(quint64);
static long long int ans;
**static long long int currVal;**
and your function:
QString getNewVal(qint64 nextDig)
is not part of the class.
This
static long long int currVal;
is private!
try:
public:
static long long int currVal;
or create a getter method for that.
also you can make the getNewVal a friend function of your class:
public:
friend QString ::getNewVal(qint64 nextDig);
You need to specify that getNewVal belongs to Calculator
QString Calculator::getNewVal(quint64 nextDig)
// ^^^^^^^^^^ ^
// This was missing |
// |
// Add 'u' above to match the declaration
Otherwise, C++ thinks that this is a free-standing function (despite the fact that you have declared a member function with the same name inside Calculator).
You also need to move the two definitions
long long int Calculator::ans = 0;
long long int Calculator::currVal = 0;
from the header file to the implementation file.