So, I am working on a side-project to keep my c++ skills fresh (it has been many years since I have done work in c++). I am working on something where I will be using SQLite. I have a wrapper around the SQLite code. One of the things I am noticing is that SQLite uses c-style callback functions in its sqlite3_exec(...) function.
I would like to have the callback function be an object method, as I would like it to be able to modify object variables but am unsure of how to do this exactly. I have checked other similar questions on stackoverflow but came away with nothing helpful.
Here is how I am declaring my wrapper class:
class DBAdapter
{
private:
sqlite3* db;
int getUserRecords(std::string);
std::vector<USER_RECORD> records;
int callbackSel(void*, int , char**, char**);
public:
DBAdapter();
~DBAdapter();
int open(std::string);
void close();
int insertRecord();
int deleteRecord();
int getNumUserRecords();
};
Here is how I am trying to use the callback (callbackSel), from within getNumUserRecords:
int DBAdapter::getUserRecords(std::string name)
{
std::string sql = "SELECT" + name + " from USERS";
char* ErrMsg;
char* data;
int retval = sqlite3_exec(db,sql.c_str(),this->callbackSel,data,&ErrMsg);
return retval;
}
The error message I am getting is:
error: ‘int (* DBAdapter::callbackSel)(void*, int, char**, char**)’ is not a static member of ‘class DBAdapter’
My problem is, if I make this a static function, I won't be able to have access to my vector, records, right? Is there any way around this?
Is there any way around this?
I don't know for sqlite API specifically, but usually c-style callbacks support to have user data passed from a void* pointer (I'd guess the 1st parameter of that signature you mention). What one typically does is:
Declare a static class function to specify as callback function pointer
Implement that function to cast the passed user data pointer to a pointer to your class instance and call a member function
Have a member function defined in the class that provides the implementation you want
Pass a pointer to your handling class instance, when you're going to register the static member function pointer with the C API
I hope this points out the right direction.
Related
I'm trying to wrap, in a C++ class, a server that I wrote using mongoose (a C library). The problem is that I'm trying to pass the function ev_handler to the mg_create_server(), which create the instance of the server in mongoose. But it gives a casting error I believe:
src/Server.cpp:16:44: error: cannot convert 'Server::ev_handler' from
type 'int (Server::)(mg_connection*, mg_event)' to type 'mg_handler_t
{aka int (*)(mg_connection*, mg_event)}' server =
mg_create_server(NULL, ev_handler);
I tried to make ev_handler static but it has send_index_page(conn) that has to be inside the wrapper class.
void Server::start() {
struct mg_server *server;
int numberOfObjects;
_application = new Application();
_application->start();
// Create and configure the server
server = mg_create_server(NULL, ev_handler);
//... more code here ...
}
int Server::ev_handler(struct mg_connection *conn, enum mg_event ev) {
switch (ev) {
case MG_AUTH: return MG_TRUE;
case MG_REQUEST: return send_index_page(conn);
default: return MG_FALSE;
}
}
Your problem is that you're passing a C++ member function to parameter that wants a free function pointer.
Mongoose is a C API and all of its callback parameters are C style functions, which in C++ are free (not member) functions.
A member function pointer is different from a free function pointer in that it needs the this , or the object on which the method is being called, in order to be called.
In your case, you are passing a member function pointer on the Server class.
When interacting which C APIs, it's common to pass a void* context object which is then passed to the callback. You then pass a pointer to a free function or a static class method (which has no this and can therefore work with C APIs). When the callback is invoked, you then cast the context object to the correct type and call a member function to get back into the object context. I can't see any such facility in Mongoose. Maybe it's there and I'm just not finding it.
You may want to try the already exising Mongoose C++ which forks the original Mongoose project to work better with C++: https://github.com/Gregwar/mongoose-cpp
The callback needs to be static, then you should use a static stub to redirect to the class instance.
Storing the instance of your class in server_param attribute of mg_server will allow to get it back in a static stub and forward it to this instance.
This could be achieve like this :
class Server
{
public:
void start() {
mg_create_server(this, ev_handlerStub);
}
static int ev_handlerStub(struct mg_connection *conn, enum mg_event ev) {
((Server*)conn->server_param)->ev_handler(conn, ev);
}
int ev_handler(struct mg_connection *conn, enum mg_event ev) {
// job to do with the class instance
}
};
Proceeding like this, allow access to class instance inside its ev_handler method.
I have a C API to a data source. To be notified that new data is available you give the API a callback in the form of a function pointer; your callback will be called when data comes in. The API’s header contains lines like this:
struct DataRecord { ... };
typedef void (*DataCallback)(DataRecord *data);
void set_data_callback(DataCallback processor);
My C++ class has an instance method with the signature
void MyClass::process_data(DataRecord *data);
and in the constructor of MyClass I’d like to set the new instance’s process_data method as the data callback for the C API. Following this answer I tried to write this code in the constructor:
typedef void (MyClass::data_callback_t)(DataRecord*);
data_callback_t callback = &MyClass::process_data;
set_data_callback(callback);
When I do this I get the error
error C2664: 'set_data_callback' : cannot convert parameter 2 from 'data_callback_t' to 'DataCallback'
There is no context in which this conversion is possible
(I am using Visual C++ 2010 Express, although I hope that doesn’t make a difference.)
How can I extract a C function pointer from an instance and a method?
You can't. MyClass::process_data can be thought of as a void(MyClass*, DataRecord*), which is the wrong type. You'd have to wrap your class pointer into the call somehow.
One approach might be to introduce a type with a static pointer:
struct MyClassCallbackHelper
{
static MyClass* myClass;
static void callback(DataRecord* record) {
myClass->process_data(record);
}
};
So that you can do:
MyClassCallbackHelper::myClass = this;
set_data_callback(&MyClassCallbackHelper::callback);
I am creating a CLR project to access my C code. It was going ok till one of the C function needed a callback. I'm not sure how to resolve this, have tried a couple of different things.
C:
typedef void(*logger_callback_t)(const char *, int);
Given the above in C, how can I assign this callback? I've tried creating a function and referencing it but getting errors. If I put the c++ function in the header it gives "pointer-to-member is not valid for a managed class". If I put it next to the function I get undeclared identifier
C++:
logger_callback_t logger = &dummy_logger_callback;
void dummy_logger_callback(const char *, int)
{
}
I'm not super clear on the issue but it seems like this is a declaration order problem. One option may be to forward declare the callback until the function is declared.
static logger_callback_t logger;
static void dummy_logger_callback(const char *, int)
{
}
logger = dummy_logger_callback;
This should work in a C context, but if your function is a method of a class or your variable is a member of a class this can get more complex. It is also complicated by what the intended storage class (static, extern etc) is for the variable and the function. Could you be more specific about the setup?
That callback should be a free function, not a member function. If you're declaring it inside a class, don't.
Valid code might look like:
// at file scope (not inside a class):
extern "C" {
void dummy_logger_callback(const char *, int)
{
// your code here
}
}
// ... and in your existing C++ code:
logger_callback_t logger = &dummy_logger_callback;
I am trying to write a nodejs bindings for a C++ library and I seem to have hit a roadblock.
I am working on trying to make all the calls to the C++ library asynchronous and thats why I am using libuv. I am basically following this tutorial.
I want to be able to call class member functions from libuv's uv_queue_work. Have a look at this code --
class test {
private:
int data;
void Work(uv_work_t *req);
void After(uv_work_t *req);
public:
Handle<Value> Async(const Arguments& args) {
HandleScope scope;
Local<Function> callback = Local<Function>::Cast(args[0]);
int status = uv_queue_work(uv_default_loop(), **something**, Work, After);
assert(status == 0);
return Undefined();
}
};
Basically I expect the Work and After functions to work on the data element of the class. However this doesnt seem to work. I have tried typecasting the pointers to Work and After after from type void test::(*)(uv_work_t*) to void (*)(uv_work_t*). But that also doesnt seem to work.
Could you guys give me some tips on how to work around this??
So as you've realized, you cannot call the member functions directly.
The second argument "something" is of type uv_work_t, which has a member "void* data".
What you will need to do is create static methods inside your class for "Work" and "After", create a uv_work_t structure, and assign data to "this".
Once that is done inside your static "Work" and "After" methods you do a static cast on "req->data" (To your class type) and then call your member functions.
For example:
uv_work_t* baton = new uv_work_t();
baton->data = this;
int status = uv_queue_work(uv_default_loop(), baton, StaticWork, StaticAfter);
And then in the static methods
test* myobj = static_cast<test>(req->data);
myobj->Work();
And similar code for the StaticAfter function
First of all I have to admit that my programming skills are pretty limited and I took over a (really small) existing C++ OOP project where I try to push my own stuff in. Unfortunately I'm experiencing a problem which goes beyond my knowledge and I hope to find some help here. I'm working with a third party library (which cannot be changed) for grabbing images from a camera and will use some placeholder names here.
The third party library has a function "ThirdPartyGrab" to start a continuous live grab and takes a pointer to a function which will be called every time a new frame arrives. So in a normal C application it goes like this:
ThirdPartyGrab (HookFunction);
"HookFunction" needs to be declared as:
long _stdcall HookFunction (long, long, void*);
or "BUF_HOOK_FUNCTION_PTR" which is declared as
typedef long (_stdcall *HOOK_FUNCTION_PTR) (long, long, void*);
Now I have a C++ application and a class "MyFrameGrabber" which should encapsulate everything I do. So I put in the hook function as a private member like this:
long _stdcall HookFunction (long, long, void*);
Also there is a public void function "StartGrab" in my class which should start the Grab. Inside I try to call:
ThirdPartyGrab (..., HookFunction, ...);
which (not surprisingly) fails. It says that the function call to MyFrameGrabber::HookFunction misses the argument list and I should try to use &MyFrameGrabber::HookFunction to create a pointer instead. However passing "&MyFrameGrabber::HookFunction" instead results in another error that this cannot be converted to BUF_HOOK_FUNCTION_PTR.
After reading through the C++ FAQ function pointers I think I understand the problem but can't make up a solution. I tried to make the hook function static but this also results in a conversion error. I also thought of putting the hook function outside of the class but I need to use class functions inside the hook function. Is there another way or do I need to change my whole concept?
EDIT 14.01.08:
I tested the singleton workaround since I cannot change the third party library and the void pointer is only for data that is used inside the hook function. Unfortunately it didn't worked out of the box like I hoped.... I don't know if the static function needs to be in a separate class so I put it in my "MyFrameGrabber" class:
static MyFrameGrabber& instance()
{
static MyFrameGrabber _instance;
return _instance;
}
long Hook(long, long, void*); // Implementation is in a separate cpp file
In my cpp file I have the call_hook function:
long MFTYPE call_hook(long x, MIL_ID y, void MPTYPE *z)
{
return MyFrameGrabber::instance().Hook(x,y,z);
}
void
MyFrameGrabber::grab ()
{
ThirdPartyGrab(..., call_hook, ...);
}
But this gives me an error in static MatroxFrameGrabber _instance; that no matching standard constructor is found. That's correct because my MyFrameGrabber constructor looks like this:
MyFrameGrabber (void* x,
const std::string &y, int z,
std::string &zz);
I tried to put in an empty constructor MyFrameGrabber(); but this results in a linker error. Should I pass empty parameters to the MyFrameGrabber constructor in the singleton? Or do I need to have a separate Hook Class and if yes how could I access MyFrameGrabber functions? Thanks in advance.
SECOND EDIT 15.01.08:
I applied the changes and it compiles and links now. Unfortunately I cannot test this at runtime yet because it's a DLL and I have no Debug Caller Exe yet and there are other problems during initialization etc. I will mark the post as answer because I'm sure this is the right way to do this.
Your private member method has an implicit this pointer as first argument. If you write that out, it's obvious that the function signatures do not match.
You need to write a static member function, which can be passed as the callback-function to the library. The last argument to the HookFunction, a void*, looks to me very much like a cookie, where one can pass ones own pointer in.
So, all in all, it should be something like this:
class MyClass {
long MyCallback(long, long) {
// implement your callback code here
}
static long __stdcall ThirdPartyGrabCallback(long a, long b, void* self) {
return reinterpret_cast<MyClass*>(self)->MyCallback(a, b);
}
public:
void StartGrab() {
ThirdPartyGrab(..., &MyClass::ThirdPartyGrabCallback, ..., this, ...);
}
};
This of course only works if the void* argument is doing what I said. The position of the this in the ThirdPartyGrab() call should be easy to find when having the complete function signature including the parameter names available.
The reason "&MyFrameGrabber::HookFunction" cannot be converted to a BUF_HOOK_FUNCTION_PTR is that, being a member of the class, it has implicitly as first parameter the "this" pointer, thus you cannot convert a member function to a non-member function: the two signatures look the same but are actually different.
I would declare an interface, defining the function to call, have your class implement it and pass the object itself instead of the callback (you can think of an interface as the object-oriented replacement of a function pointer):
class IHookInterface{
public:
virtual long HookFunction(long, long, void*) = 0;
};
class HookClass : public IHookInterface{
public:
virtual long Hook(long, long, void*) {
// your code here...
}
};
// new definition:
ThirdPartyGrab (..., IHookInterface, ...);
EDIT - other possible solution in case you cannot modify the library: use a singleton rather than a static function.
class HookClass{
public:
static HookClass& instance(){
static HookClass _instance;
return _instance;
}
long Hook(long, long, void*) {
// your code here...
}
};
long call_hook(long x,long y,void * z){
return HookClass::instance().Hook(x,y,z);
}
SECOND EDIT: you might slightly modify the singleton class with an initialization method to call the constructor with the proper parameters, but maybe it is not more elegant than the following solution, which is simpler:
class HookClass{
public:
HookClass(string x,string y...){
}
long Hook(long, long, void*) {
// your code here...
}
};
static HookClass * hook_instance = 0;
long call_hook(long x,long y,void * z){
if (0 != hook_instance){
return hook_instance->Hook(x,y,z);
}
}
int main(){
hook_instance = new HookClass("x","y");
ThirdPartyGrab(..., call_hook, ...);
}