Void Wrappers for Nonvoid Functions With An Argument - c++

So, I have the following situation:
I'm coding for the mbed online compliler, on a low-memory microcontroller.
Real Time performance is very important, I want this to take less than a microsecond. 10 microseconds would be tolerable.
I'm using their timeout library, which provides an API for calling an ISR after a specified time, but requires that the ISR be a void/void function. (including a member function.
void TimeoutCallback(void) { do stuff that I want to do on timeout.} // ISR
Timeout to;
to.attach_us(&TimeoutCallback, 750) // Call TimeoutCallback in 750 us.
I created a vector of Timeout objects, which all get set at once, to the same function, with a different amount of time. I want to somehow pass into the TimeoutCallback which Timeout object called it.
My initial thought was to overload the Timeout class to allow it to accept int function(int) function pointers, and to accept a number in the overloaded attach function that gets passed to said function pointer. However, I'm unsure whether this is actually practical given the messy (and device-specific) inheritance of the Timeout class.
Now, I wonder whether there is a way to programatically create a void/void function that wraps a void/int function, and included a changeable reference int which is passed to the wrapped function.

While Tony D's solution is appropriate if using the mbed Ticker class, there is an alternative method using the mbed RtosTimer.
The RtosTimer constructor takes a void* argument that is passed to the handler on timeout. The handler has the signature:
void handler(void const* n)
Where n is the pointer argument passed to the constructor and can be used to ID the specific timeout.
Unlike Ticker where the timeout function runs in the interrupt context, for RtosTimer the handler runs as a thread, so gives greater flexibility, but potentially greater latency.

As your library can call member functions, you can create an adapter ala...
template <typename Func, Func func>
struct Adapter
{
Adapter(int n) : n_(n) { }
void f() { func(n_); }
int n_;
};
To use it:
Adapter<void(*)(int), My_Function_Expecting_An_Int> adapter(the_int);
to.attach_us(&adapter, &decltype(adapter)::f, timeout_us);
Make sure the adapter's lifetime lasts until the callback....
To call a member function:
#include <iostream>
#include <string>
#include <vector>
struct MyObj
{
void f(int n) { std::cout <<"hi " << n << "\n"; }
};
template <typename Class, typename PFunc>
struct Adapter
{
Adapter(Class& object, PFunc pFunc, int n) : object_(object), pFunc_(pFunc), n_(n) { }
void f() { (object_.*pFunc_)(n_); }
Class& object_;
PFunc pFunc_;
int n_;
};
int main()
{
MyObj myObj;
Adapter<MyObj, void(MyObj::*)(int)> adapter(myObj, &MyObj::f, 43);
adapter.f();
}

Related

Passing a locally-created lambda for use in a callback, then going out of scope

I'm using some (somewhat C-ish) library which involves a callback mechanism. The callback functions I can provide it take a void* as a parameter so you can pass arbitrary stuff to them. For the sake of this question let's assume the lambda doesn't take any parameters, but it does capture stuff.
Now, I need to have my callback function invoke a lambda - and it must get this lambda somehow via the void *, i.e. we have
void my_callback(void * arbitrary_stuff) {
/* magic... and somehow the lambda passed */
/* through `arbitrary_stuff` is invoked. */
}
// ...
template <T>
void adapted_add_callback(MagicTypeInvolvingT actual_callback) {
/* more magic */
libFooAddCallback(my_callback, something_based_on_actual_callback);
}
// ...
void baz();
void bar() {
int x;
adapted_add_callback([x]() { /* do something with x */ });
adapted_add_callback(baz);
}
and I want to know what to replace magic, more_magic and MagicTypeInvolvingT with.
Other than the typing challenge here, what I'm worried about, obviously, is how to make sure the data the lambda encapsulates is available on the stack for eventual use, as otherwise I should probably get some kind of segmentation fault.
Notes:
my_callback() should be synchronous, in the sense that it'll execute the lambda on whatever thread it is on and return when it returns. It's either the fooLibrary or the lambda itself which do asynchronicity.
the most straightforward way might be ( assuming the C function is guaranteed to invoke the callback exactly once, and that the lambda is valid at callback point )
void my_callback(void * arbitrary_stuff) {
(*std::unique_ptr{ static_cast<std::function<void()>*>(arbitrary_stuff) })();
}
void adapted_add_callback( std::function<void()> actual_callback ) {
libFooAddCallback(my_callback, new auto( std::move(actual_callback) ) );
}
if you don't want the function<> overhead you'll need to implement your own type erasure ...
You have a couple of issues here.
One is that you can't depend on passing the lambda itself as a void *, so you'll pretty much need to pass a pointer to the lambda (well, the closure created from the lambda, if you want to be precise). That means you'll need to ensure that the lambda remains valid until the callback completes.
The second is a question about how those captures happen - capture by value, or by reference? If you capture by value, everything's fine. If you capture by reference, you also need to ensure that anything you've captured remains valid until the callback completes. If you capture a global by reference, that should normally be fine--but if you capture a local by reference, then the local (even potentially) goes out of scope before the lambda is invoked, using the reference will cause undefined behavior.
I went in a way similar to Massimiliano Janes', but without the overhead of std::function. You have to ensure that the callback is called only once by the library.
using Callback = void(*)(void*);
// Probes the type of the argument and generates a suitable cast & invoke stub
// Caution: self-destructs after use!
template <class F>
Callback cbkWrap(F &) {
return [](void *data) {
std::unique_ptr<F> retrieved(static_cast<F*>(data));
(*retrieved)();
};
}
// Moves the functor into a dynamically-allocated one
template <class F>
void *cbkFunc(F &f) {
return new F{std::move(f)};
}
int main() {
int x = 42;
auto lambda = [&x] { std::cout << x << '\n'; };
libFooAddCallback(cbkWrap(lambda), cbkFunc(lambda));
}
See it live on Coliru
If you can ensure that the lambda outlives the potential calls, you can get rid of the dynamic memory allocations and simply pas a pointer to it as data:
// Probes the type of the argument and generates a suitable cast & invoke stub
template <class F>
Callback cbkWrap(F &) {
return [](void *data) {
auto retrieved = static_cast<F*>(data);
(*retrieved)();
};
}
int main() {
int x = 42;
auto lambda = [&x] { std::cout << x << '\n'; };
libFooAddCallback(cbkWrap(lambda), &lambda);
}
See it live on Coliru
There is unfortunately no way to give ownership of the lamba to the library without knowing exactly how many times it will be called.

Is it safe to convert a template lambda to a `void *`?

I'm working on implementing fibers using coroutines implemented in assembler. The coroutines work by cocall to change stack.
I'd like to expose this in C++ using a higher level interface, as cocall assembly can only handle a single void* argument.
In order to handle template lambdas, I've experimented with converting them to a void* and found that while it compiles and works, I was left wondering if it was safe to do so, assuming ownership semantics of the stack (which are preserved by fibers).
template <typename FunctionT>
struct Coentry
{
static void coentry(void * arg)
{
// Is this safe?
FunctionT * function = reinterpret_cast<FunctionT *>(arg);
(*function)();
}
static void invoke(FunctionT function)
{
coentry(reinterpret_cast<void *>(&function));
}
};
template <typename FunctionT>
void coentry(FunctionT function)
{
Coentry<FunctionT>::invoke(function);
}
int main(int argc, const char * argv[]) {
auto f = [&]{
std::cerr << "Hello World!" << std::endl;
};
coentry(f);
}
Is this safe and additionally, is it efficient? By converting to a void* am I forcing the compiler to choose a less efficient representation?
Additionally, by invoking coentry(void*) on a different stack, but the original invoke(FunctionT) has returned, is there a chance that the stack might be invalid to resume? (would be similar to, say invoking within a std::thread I guess).
Everything done above is defined behaviour. The only performance hit is that inlining something aliased thro7gh a void pointer could be slightly harder.
However, the lambda is an actual value, and if stored in automatic storage only lasts as long as the stored-in stack frame does.
You can fix this a number of ways. std::function is one, another is to store the lambda in a shared_ptr<void> or unique_ptr<void, void(*)(void*)>. If you do not need type erasure, you can even store the lambda in a struct with deduced type.
The first two are easy. The third;
template <typename FunctionT>
struct Coentry {
FunctionT f;
static void coentry(void * arg)
{
auto* self = reinterpret_cast<Coentry*>(arg);
(self->f)();
}
Coentry(FunctionT fin):f(sts::move(fin)){}
};
template<class FunctionT>
Coentry<FunctionT> make_coentry( FunctionT f ){ return {std::move(f)}; }
now keep your Coentry around long enough until the task completes.
The details of how you manage lifetime depend on the structure of the rest of your problem.

Dynamically create a function and get a pointer

I am using Arduino and motor encoders to track the rotations of a motor. To do this, I am using interrupts on the Arduino. I can create a function, an ISR, that will be executed by the processor whenever the signal changes on a pin. That Interrupt/ISR combinations works like this:
void setup() {
attachInterrupt(1,ISR_function,FALLING);
}
void ISR_function() {
// do something
}
Seeing as I have multiple motors with encoders, I decided I would make a class to handle this. However, the attachInterrupt method requires a function pointer, and I am aware that in C++ you cannot have a pointer to a method function of an instance of an object. So something like this will not work:
class Encoder {
public:
Encoder(void);
void ISR_function(void);
private:
// Various private members
}
Encoder::Encoder() {
attachInterrupt(1,ISR_function,FALLING);
}
Encoder::ISR_function() {
// Do some interrupt things with private members
}
Because ISR_function is not static. The ISR_function however executes code that is dependent on the the private data members of each specific instance.
Is it possible to create a function dynamically? And then retrieve a pointer to that function? Almost like in javascript:
class Encoder {
public:
Encoder(void);
void* ISR_function(void);
private:
// Various private members
}
Encoder::Encoder() {
attachInterrupt(1,ISR_function(),FALLING);
}
Encoder::ISR_function() {
return dynamicFunctionPointer;
}
Is this possible? If not, how can accomplish what I am trying to do without manually creating separate static ISR_functions.
// type of an interrupt service routine pointer
using ISR = void(*)();
// a fake version of the environment we are working with
// for testing purposes
namespace fake_environment {
enum bob{FALLING};
ISR isrs[100] = {0};
void attachInterrupt(int i, void(*f)(), bob) {
isrs[i] = f;
}
void runInterrupt(int i) {
isrs[i]();
}
}
// type storing a pointer to member function
// as a compile-time constant
template<class T, void(T::*m)()>
struct pmf {};
// stores a pointer to a class instance
// and a member function. Invokes it
// when called with operator(). Type erases
// stuff down to void pointers.
struct funcoid {
using pfunc = void(*)(void*);
pfunc pf = 0;
void* pv = 0;
void operator()()const { pf(pv); }
template<class T, void(T::*m)()>
funcoid(T* t, pmf<T,m>):
pv(t)
{
// create a lambda, then decay it into a function pointer
// this stateless lambda takes a void* which it casts to a T*
// then invokes the member function m on it.
pf = +[](void* pt) {
(static_cast<T*>(pt)->*m)();
};
}
funcoid()=default;
};
// a global array of interrupts, which have a this pointer
// and a member function pointer type erased:
namespace client {
enum {interrupt_count = 20};
std::array<funcoid, interrupt_count> interrupt_table = {{}};
// with a bit of work, could replace this with a std::vector
}
// some metaprogramming utility code
// this lets me iterate over a set of size_t at compile time
// without writing extra helper functions at point of use.
namespace utility {
template<std::size_t...Is>
auto index_over( std::index_sequence<Is...> ) {
return [](auto&& f)->decltype(auto) {
return f(std::integral_constant<std::size_t, Is>{}...);
};
}
template<std::size_t N>
auto index_upto( std::integral_constant<std::size_t, N> ={} ) {
return index_over( std::make_index_sequence<N>{} );
}
}
// builds an array of interrupt service routines
// that invoke the same-index interrupt_table above.
namespace client {
// in g++, you'd write a helper function taking an `index_sequence`
// and take the code out of that lambda and build the array there:
std::array<ISR, interrupt_count> make_isrs() {
// creates an array of ISRs that invoke the corresponding element in interrupt_table.
// have to do it at compile time, because we are generating 20 different functions
// each one "knows" its index, then storing pointers to them.
// Could be done with a lot of copy-pasta or a macro
return ::utility::index_upto< interrupt_count >()(
[](auto...Is)->std::array<ISR, interrupt_count>{
return {{ []{ interrupt_table[decltype(Is)::value](); }... }};
}
);
}
// isr is a table of `void(*)()`, suitable for use
// by your interrupt API. Each function pointer "knows" its
// index, which it uses to invoke the appropraite `interrupt_table`
// above.
auto isr = make_isrs();
// with a bit of work, could replace this with a std::vector
}
// interrupt is the interrupt number
// index is the index in our private table (0 to 19 inclusive)
// t is the object we want to use
// mf is the member function we call
// kind is FALLING or RISING or the like
// index must be unique, that is your job.
template<class T, void(T::*m)()>
void add_interrupt( int interrupt, int index, T* t, pmf<T, m> mf, fake_environment::bob kind ) {
client::interrupt_table[index] = {t, mf};
fake_environment::attachInterrupt(interrupt,client::isr[index],kind);
}
class Encoder {
public:
Encoder():Encoder(1, 7) {};
Encoder(int interrupt, int index);
void ISR_function(void);
// my choice for some state:
std::string my_name;
};
Encoder::Encoder(int interrupt, int index) {
add_interrupt( interrupt, index, this, pmf<Encoder, &Encoder::ISR_function>{}, fake_environment::FALLING );
}
void Encoder::ISR_function() {
// display state:
std::cout << my_name << "\n";
}
int main() {
Encoder e0;
e0.my_name = "Hello World";
fake_environment::runInterrupt(1);
Encoder e1(0, 10);
e1.my_name = "Goodbye World";
fake_environment::runInterrupt(0);
}
Does not compile in g++ and uses C++14.
Does solve your problem. g++ problem is in make_isrs, which can be replaced by verbose copy-paste initialization. C++14 is from index_upto and index_over, which can similarly be reworked for C++11.
Live example.
However, ISRs are supposed to be minmal; I suspect you should just record the message and handle it elsewhere instead of interacting with object state.
To call a member function you need an instance to invoke it on, so it doesn't seem like a good choice to use for interrupts.
From pointers-to-members:
A member function is meaningless without an object to invoke it on.
Non-static member functions have a hidden parameter that corresponds to the this pointer. The this pointer points to the instance data for the object. The interrupt hardware/firmware in the system is not capable of providing the this pointer argument. You must use “normal” functions (non class members) or static member functions as interrupt service routines.
One possible solution is to use a static member as the interrupt service routine and have that function look somewhere to find the instance/member pair that should be called on interrupt. Thus the effect is that a member function is invoked on an interrupt, but for technical reasons you need to call an intermediate function first.
First of all, you can extract pointer to a class method and call it:
auto my_method_ptr = &MyClass::my_method;
....
(myClassInstance->*my_method_ptr)(); // calling via class ptr
(myclassInstance.*my_method_ptr)(); // calling via class ref
This basically passes myClassInstance pointer to MyClass::my_method as an implicit argument, accessible via this.
Unfortunately, AVR interrupt controller can't call class method, as the hardware operate on simple pointers only and can't call that method with implicit argument. You'll need a wrapper function for this.
MotorEncoderClass g_motor; // g_ for global
void my_isr() {
g_motor.do_something();
}
int main() {
// init g_motor with relevant data
// install my_isr handler
// enable interrupts
// ... do rest of stuff
return 0;
}
Create your class instance as a global variable.
Create ordinary function that calls that method
Initialize your motor class with relevant data
Install my_isr as IRQ handler.
Press start to begin :)

Get call identifier or address of a function

Suppose that I have this code:
class MyClass
{
public:
void SomeFunction()
{
// Find somehow if this is first, second, or third call of a function in a main loop
// If the function is called first time create new variables that will be used just for this function call
}
};
MyClass myClassObject;
int main()
{
myClassObject.SomeFunction(); // First call
myClassObject.SomeFunction(); // Second call
myClassObject.SomeFunction(); // Third call
}
How can I know inside function what number of call is it?
Note that I will probably have 100 function calls placed in code. Also this should work in Visual Studio on Windows and Clang on Mac.
I had one workaround:
void SomeFunction(const char* indetifier = "address")
{
CheckAddress(indetifier); // This will check if address is stored. If it is not, create variables, if it is, if addresses matches use variables that are tied to that address.
}
I tried not to assign a new string to an "indetifier" and to let it to use default string ("address"). This of course didn't worked well as compiler will optimize "indetifier", so I was thinking that maybe a solution would be to disable optimizations for that variable, but I didn't because there should be some more elegant solution.
Also one thing came on my mind, maybe I could force inline a function and then get it's address, but this also seams like bad workaround.
I could also create new classes for every call but I would like to avoid this as there will be a lot of function calls and I don't want to think 100 different names.
If there is a way to create class object only at first call this would be awesome.
I hope that you understand what I want, sorry if something is not that clear as I am beginner coder.. :D
EDIT:
I can't use static for variables in a class because software that I am developing is a plugin that could have multiple instances loaded inside host and this will probably mess up the variables. I have tested static variables and if I create for example "static int value" anywhere and write something in it in one instance of a plugin this "value" will be updated for all instances of a plugin and this is not something that I want.
void SomeFunction()
{
// Find somehow if this is first, second, or third call of a function in a main loop
// If the function is called first time create new variables that will be used just for this function call
}
If the first call is to be tracked per object, then you need a member variable that keeps track of how many times SomeFuntion has been called for that object.
If the first call is to be tracked independent of objects, then you can use a static function variable that keeps track of how many times SomeFuntion has been called for that object.
I can't use static for variables in a class because software that I am developing is a plugin that could have multiple instances loaded inside host and this will probably mess up the variables. I have tested static variables and if I create for example "static int value" anywhere and write something in it in one instance of a plugin this "value" will be updated for all instances of a plugin and this is not something that I want.
So make a non-static counter?
class MyClass {
int count;
public:
MyClass () : count(0) { }
void SomeFunction () {
++ count;
// do stuff with 'count'
}
};
MyClass myClassObject;
int main () {
myClassObject.SomeFunction(); // First call
myClassObject.SomeFunction(); // Second call
myClassObject.SomeFunction(); // Third call
}
Or just pass it as a parameter...
class MyClass {
public:
void SomeFunction (int count) {
// do stuff with 'count'
}
};
MyClass myClassObject;
int main () {
myClassObject.SomeFunction(1); // First call
myClassObject.SomeFunction(2); // Second call
myClassObject.SomeFunction(3); // Third call
}
But I'm really wondering what you're actually trying to do, and I highly suggest sitting back and rethinking this whole thing, because there are a number of red flags / confusing points here...
If you're only interested in checking whether it's the first call, you can add a bool SomeFunction_first_call; to the MyClass, to act as a flag. The constructor sets the bool to true. MyClass::SomeFunction() uses the conditional check if (SomeFunction_first_call) /* ... */ to determine whether it's the first call, as follows:
class MyClass
{
bool SomeFunction_first_call;
public:
MyClass() : SomeFunction_first_call(true) {}
void SomeFunction()
{
if (SomeFunction_first_call)
{
// This code only executes on first call.
do_something();
// Successfully handled first call, set flag to false.
SomeFunction_first_call = false;
}
// This code always executes.
do_something();
}
};
Similarly, if you're only concerned about the first HOWEVER_MANY_CALLS calls, where HOWEVER_MANY_CALLS is a number, you can use something like this:
#include <cstdint>
class MyClass
{
uint8_t SomeFunction_calls;
public:
MyClass() : SomeFunction_calls(0) {}
void SomeFunction()
{
// This segment will be executed until (SomeFunction_calls == HOWEVER_MANY_CALLS).
// After this, the segment will be skipped, and the counter will no longer increment.
if (SomeFunction_calls < HOWEVER_MANY_CALLS)
{
// This code only executes on first HOWEVER_MANY_CALLS calls.
do_something();
// Increment counter.
++SomeFunction_calls;
}
// This code always executes.
do_something();
}
};
Make sure to use the appropriately signed variable for the number of calls that need special handling (i.e. uint8_t for 0..255, uint16_t for 256..65,535, etc.). If different instances of MyClass will need to keep track of a different number of calls, then use a non-type template parameter to indicate this, and optionally, a defaulted typename to indicate what type the counter should be.
#include <cstdint>
template<uint64_t N, typename T = uint64_t>
class MyClass {
T SomeFunction_calls;
...
void SomeFunction()
{
if (SomeFunction_calls < N) {
...
}
...
}
};
In this case, a MyClass<4> will have special treatment for the first 4 calls to SomeFunction(), a MyClass<4444444444444444444> will have special treatment for the first 4,444,444,444,444,444,444 calls, and so on. The counter will default to uint64_t, as that should be large enough to hold the value; when only a smaller number of calls need special treatment, you can specify a smaller type, such as MyClass<4, uint8_t> or MyClass<444444444, uint32_t>.
In C++ you can use the static keyword in a local variable context to create the object only once at the first call:
#include <iostream>
struct MyObject {
MyObject() {
std::cout << "Creating instance " << this << "\n";
};
};
void foo() {
static MyObject my_instance;
std::cout << "... inside function foo ...\n";
}
int main(int argc, const char *argv[]) {
std::cout << "About to call foo...\n";
foo();
std::cout << "... second call ...\n";
foo();
std::cout << "... third call ...\n";
foo();
return 0;
}
With the above code you will notice that only on object MyObject will be created, on the first call to foo.
Note that if your function is a template then for each instantiation of the template you will get another distinct static variable. For example with:
template<int N>
void foo() {
static MyObject my_instance;
std::cout << "... inside function foo ...\n";
}
the all the calls to foo<1>() will use the same variable but calling instead foo<2>() will access another copy of the function (another instantiation of the function template), that will have its own distinct static variable created on the first call to foo<2>(). All static variables that have been initialized will be destroyed after the end of main when the program terminates.

How to use lambda functions or std::function with an API that takes function pointers?

Suppose I want to implement a simple abstraction over pthreads.
(or any C API that takes function pointers for callbacks or threads).
Like std::thread, I want the interface to be able to take function objects in general.
How do I bridge the gap in a way that works for all cases?
(That includes binds, lambda functions, etc.)
I know about the std::function::target but afaik, it does not do what I need.
If the API takes functions with a void* for user data as, e.g., pthread_create() does, you'd pass a pointer to the function as user data, call a trampoline which casts the user data to your function type, and calls the function. For example:
#include <functional>
#include <pthread.h>
extern "C" void* trampoline(void* userData) {
return (*static_cast<std::function<void*()>*>(userData))();
}
void* start() {
// ...
return 0;
}
int main() {
pthread_t thread;
std::function<void*()> entry(start);
pthread_create(&thread, 0, &trampoline, &entry);
// ...
}
The immediate implication is, however, that the function object life-time isn't easily controlled. In the example above the std::function<void*()> object happens to live long enough but it isn't always as easy.
If the function you try to call doesn't have a user data argument, you are pretty much out of luck. You might get away with using global objects but it is almost certainly a rather fragile approach.
A lambda function can be used anywhere that takes regular function pointers. In other words, it can be used wherever you would use regular functions/pointers to functions..
Example: https://ideone.com/4CJjlL
#include <iostream>
void voidfunc(void (*func_ptr)(void))
{
func_ptr();
}
void funcwithargs(void (*func_ptr)(int, char, std::string), int a, char b, std::string c)
{
func_ptr(a, b, c);
}
int main()
{
auto vf = []{std::cout<<"Called void func..\n";};
auto vfwa = [](int a, char b, std::string c) {std::cout<<"Called func with args with: "<<a<<b<<" "<<c<<"\n";};
voidfunc(vf);
funcwithargs(vfwa, 10, 'x', " + 3");
return 0;
}
Likewise, you can use std::function instead of the function pointer..