Passing an argument to a void(*)(void*) - c++

I am wrapping some sqlite3 C code in C++ and am confused about this type of argument void(*)(void*) in this function
int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
So my wrapper looks like
int Query::Blob(int index, const void* blob, int blob_size, void* memory_management){
return sqlite3_bind_blob(stmt, index, blobl, blob_size, memory_management);
}
I should be able to pass the following to the last argument
Some function to free the blob memory
Either SQLITE_STATIC or SQLITE_TRANSIENT defines
The two defines are unsurprisingly defined as
typedef void (*sqlite_3_destructor_type)(void*);
But I really don't understand the void/void syntax. How can I wrap that in my C++ method to accept a function like delete or the defines?

The type void(*)(void*) is a pointer to a non-member function that takes a single argument of type void * and returns void.
So if your memory_management function is declared as:
void memory_management(void *);
Then it matches this definition, and Query::Blob should be defined as:
int Query::Blob(int index, const void* blob, int blob_size, void (*memory_management)(void *)){
return sqlite3_bind_blob(stmt, index, blobl, blob_size, memory_management);
}

This means that you need to provide a call back that takes one argument, a pointer to void and returns nothing. This has to be a free function (not a non-static method of a class)
Indeed, free is such a function. You can use a delete-like as well:
void myfree(void* data)
{
delete static_cast<MyObject*>(data);
}
You loose type-safety, but if this is to free an object passed as void* somewhere else and also used in callback, this is defined behavior.

Related

What does void (* const ivt[])(void) mean?

I'm reading the book Embedded Systems Architecture by Daniele Lacamera. In Chapter 4,The Boot-Up code
__attribute__ ((section(".isr_vector"))) void (* const ivt[])(void) =
{
(void (*) (void))(END_STACK),
isr_reset,
//...
};
I don't understand void (* const ivt[])(void), is it the array? If it's the array what does (void) mean?
Install the tool cdecl and ask it to explain things to you:
mrvn#ryzen:~$ cdecl
Type `help' or `?' for help
cdecl> explain void (* const ivt[])(void)
declare ivt as array of const pointer to function (void) returning void
This is the declaration of an interrupt vector table for a microcontroller, likely an ARM Cortex M.
__attribute__ ((section(".isr_vector"))) is a non-standard gcc extension assigning the variable to a specific section in memory (absolute address). You'll find .isr_vector in the corresponding linker script.
Regarding void (* const ivt[])(void):
void (*f)(void) would create a function pointer (to a function taking no arguments and returning no value - which is true for all interrupt service routines).
void (*f[])(void) would create an array of function pointers. Since no size of the array is specified, the size will be determined by the following initializer list.
void (* const ivt[])(void) adding the const keyword will make the array of function pointers read-only, which is a requirement since it should get allocated in flash and never changed in run-time.
(void (*) (void))(END_STACK) could cast an integer END_STACK to a function pointer. Alternatively this could also be a dirty, strictly speaking invalid cast from a struct or other object into a function pointer. The target appears to be an ARM core where the default stack pointer is stored at the bottom of the interrupt vector table, then then sp is set automatically by the hardware.
isr_reset is the first interrupt, the reset vector.
It is an array named ivt holding constant pointers to functions that take no parameters and return void.
i dot't understading void (* const ivt[])(void), is it the array?
Yes, ivt is an array of constant pointers to function that accepts no arguments and returns nothing.
The type of elements of ivt array is
void (* const)(void)
which means constant pointer to function which accepts no arguments and returns nothing.
If it's the array what does (void) mean?
It means function accepts no arguments.
ivt is an array of constant pointers to functions that takes no parameters and have the return type void.
Perhaps an example might help understand the situation better:
void func1()
{
std::cout<<"func1 called"<<std::endl;
}
void func2()
{
std::cout<<"func2 called"<<std::endl;
}
void foo()
{
std::cout<<"foo called"<<std::endl;
}
void foobar()
{
}
int main()
{
//----------------vvv---------------------------------> ivt is an array of const pointers to a function with return type of void and having 0 parameters
void (* const ivt[])(void) = {func1, func2, foo};
//--------------------------------^^^^^--^^^^^--^^^---> add pointers to these 3 functions into the array
//iterate through the elements in the array and call the member functinos
for(void (*const PTR)(void): ivt)
{
PTR();
//-----------v---------------------------------------->this assignment won't work because pointers are themselves const so you can make them point to another function
//PTR = foobar;
}
}
The output of the above program is:
func1 called
func2 called
foo called

typedef void (*print_type) (const char*); [duplicate]

This question already has answers here:
Typedef function pointer?
(6 answers)
Closed 5 years ago.
While exploring some code, I found the following in a header file:
typedef void (*print_type) (const char*);
What does this line mean? I know that typedef is used to make specific word (in our case *print_type) to represent a specific type (in our case const char*).
But my question is why we have to use void?
This:
void foo(const char*);
declares foo as a function that takes a const char* argument and returns void (i.e., it doesn't return anything). (It would have to be defined somewhere for you to be able to call it.)
This:
void (*bar)(const char*);
defines bar as a pointer object. It's a pointer to a function that has the same type as foo, above.
By adding the typedef keyword, this:
typedef void (*print_type)(const char*);
defined print_type, not as an object of that pointer-to-function type, but as an alias for that pointer-to-function type.
What is it?
typedef void (*print_type) (const char*);
The typedef tells the compiler that the data type print_type is a pointer to a function which accepts const char* as an argument and does not return a value.
... and it has nothing to do with a DLL
Function Pointers
We declare a function as follows:
ret-type identifier(parameters)
int f(double x)
Given that for something declared as int a, the pointer to it is declared as int *a (adding a * after the data type), it is natural for someone to come up with a way to declare a function pointer as follows:
int *f(double);
There's a catch here. That is actually a declaration of a function which accepts a double as an argument and returns a int*.
We need to explicitly tell the compiler that it is not a function returning a pointer; rather it is a pointer to a function. We do this by placing brackets (parenthesis has higher precedence) around *f.
int (*f)(double);
Let's take another example:
int* myfunc(int a[], char b);
To declare an array of function pointers which point to a function with the above signature, we write:
int* (*ptr[])(int[], char);
There is a trick known as Spiral Rule which is quite useful in finding out what a complicated data type is.
Using typedef
Things can get pretty complicated with function pointers. To keep the code readable and neat, we prefer giving a single symbol type name to function pointer types using typedef.
typedef int (*ptrFunc_t)(int, char);
This allows you to declare a pointer to a function which accepts an int and a char as arguments and returns an int as follows:
ptrFunc_t myptr;
It is creating a typedef of a pointer-to-function, the function takes a const char pointer argument and retusn nothing.
Such typedefs are common in libraries that are meant for dynamic loading (that is with LoadLibrary etc), since you must load function pointers to the actual functions rather than being able to use the function name directly as you can with load-time linking.

What is void (*)() type and how to cast to such a type

What is void (*)() type in c++, how to cast a int to such type, I found it in a function like this:
function(const char*, long int, void (*)());
It's a function pointer: the address of a function with no parameters or return value.
You can't meaningfully cast an int to such a type. It's for passing a pointer to your own code for the function to call:
void my_callback() {/* do something */}
function("Hello", 42, my_callback);
Now the function can call its parameter as if it were a function, with the effect of calling your "callback" function.
In C/C++ the 'maximum munch' rule applies in evaluating expressions: from the starting point go left as much as possible to get a valid expression, then go right.
This is how a---b translates to (a--)-b and not a-(--b)
Back to your expression
void (*)()
(*) -> you have a pointer
(*)() -> you have pointer to a function what takes no parameters
void (*)() -> you have pointer to a function what takes no
parameters and does not return a value
So, your function is passed in a pointer to a function with no parameters, that returns nothing. Careful when passing in the pointer because it need to match exactly(return type and all).
Now, as far as to why you would want to do this, I can give you an practical example: the pthred_create function prototype:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
void *start_routine() is what the tread will run (like it's main) and that's why the create function needs this function pointer.
Some APIs use this method for more flexibility

c++ function taking function pointer with a default function

assume I have the following function
int watchVar(const char* var, const char* descriptor,
Color (*colorfunc)(const char* var) = yellowColorFunc)
with
Color yellowColorFunc(const void* var){
return Color::yellow();
}
I want to overload watchVar to accept functions whos parameters are char, int, float, etc, but do not want to create a default color function for each type.
g++ gives this error:
xpcc::glcd::Color (*)(const char*)' has type 'xpcc::glcd::Color(const void*)
Is there another way besides declaring colorfunc to take a void pointer and forcing the caller to cast the argument later himself?
Thanks
the function pointer is declared const char * but the yellowColorFunc is declared const void *
Your problem is that your declaring a function pointer taking a const char * but yellowColorFun takes a const void *. If c++11 is available you can use std::function like so:
auto colorFunc = std::function<int(const char *,const char *,std::function<Color(const char*)>)>();
You said in a comment that you wanted to use the function for int,float and others, what your should do in that situation is use a templated function, you really don't wanna use void*'s in c++ very often.

Who can help me explain the use of typedef in C++?

I am so confused with this code in the book :
typedef int (*healthCalcFunc) (const GameCharacter&)
and I understand that
typedef double* PDouble, means the word PDouble can be used to declare a pointer to double.
But I can't figure out the meaning of typedef int (*healthCalcFunc) (const GameCharacter&)
Is there anyone can help me to explain this?
Thanks in advance
:)
typedef int (*healthCalcFunc) (const GameCharacter&);
It introduces a name called healthCalcFunc for a type which describes a function-pointer, taking one parameter of type const GameCharacter& and returning an int.
So this means, if you've a function as:
int some_function(const GameCharacter&)
{
//...
}
Then you can create a pointer-object which would point to the above function as:
healthCalcFunc pfun = some_function;
and then use pfun in place of some_function as:
some_function(args); /normal call
pfun(args); //calling using function pointer
//it is exactly same as the previous call
And benefit with this approach is that you can pass around pfun (or some_function) to other function as:
void other_function(healthCalcFunc pfun)
{
//..
pfun(args); //invoke the function!
//..
}
healthCalcFunc pfun = some_function;
other_function(some_function);
other_function(pfun);
Here other_function will use the function pointer to invoke the function. That way, next time you can pass another function matching the function signature to other_function and other_function will invoke that another function instead.
In cases like this, operator precedence tends to get in the way.
What this creates is an alias (named healthCalcFunc) for the type "pointer to a function taking a reference to a const GameCharacter as its parameter and returning an int".
int: return type
(*healthCalcFunc): Pointer to function -- must be in parens to bind the * to the name instead of the preceding int, which would declare a function returning a pointer instead of the desired pointer to a function.
(const GameCharacter &): the parameter list for the type of function this will point at.
It's a function pointer - hopefully your book will have explained these somewhere; if not, your favourite search engine should be able to point you in the right direction.
That is typedef for a function pointer for functions which return int and take const GameCharacter& as an argument.
You can create a function pointer using healthCalcFunc hp = &MyFunc; then use it as int n = (*hp)(GameCharacter());. Here MyFunc will have this signature: int MyFunc(const GameCharecter&);.
This is a function type definition. At first glance, it's strange, but you'll get used to it. basically, what it says is, define a type named healthCalcFunc, whose return value is an integer, and takes a constant GameCharacter reference as its only argument.
In general, the form of a function pointer declaration is as follows:
typedef return_type (*new_function_typename)(typeof_arg1, typeof_arg2, ...);
And you can use it like this:
new_function_typename functor;
functor = some_other_functions_name;
// or
functor = dlsym(dlopen_handle, "some_function_name"); // for dynamic loading
int retval = functor(arg1, arg2);