Skip to content

Instantly share code, notes, and snippets.

@kara-ryli
Created October 17, 2020 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kara-ryli/6b4abc7bda2376d1dd2a54281a0c58c4 to your computer and use it in GitHub Desktop.
Save kara-ryli/6b4abc7bda2376d1dd2a54281a0c58c4 to your computer and use it in GitHub Desktop.
I'm still learning the nuances of C and C++; it's a big change from JavaScript. Here's a problem that has such a simple implementation in JS that I never considered the complexity of doing it in C++.
// This file represents a simplification of a scope problem I have interacting
// with a C SDK. Essentially:
//
// * I to pass a callback to a C function
// * The callback should call a member function of a non-static class instance
//
// I would like to achieve this without risking memory leaks and crashes, while
// also not introducing a huge amount of complexity or rearchitecting the app.
#include <iostream>
void func(void (*fn)())
{
fn();
}
class Thing
{
public:
void GetMessage()
{
std::cout << "Hello World";
}
};
// Assume is a non-singleton class instance method, though in practice
// only used once, (probably, for now) such that this may appear to work
// in a naive implementation even if something is done unsafely.
int main()
{
// Compiles, but won't fit the use case
// func([]() -> void
// {
// Thing th2;
// th2.GetMessage();
// });
Thing th;
// Won't compile
// auto fn = [&th]() -> void
// {
// th.GetMessage();
// };
// Won't compile
// auto fn = std::bind([](Thing th) -> void
// {
// th.GetMessage();
// }, th);
// Won't compile
// std::function<void()> fn = [&th]() -> void
// {
// th.GetMessage();
// };
// Seems problematic
static std::function<void()> staticFunc = [&th]() -> void
{
th.GetMessage();
};
auto fn = []() -> void
{
staticFunc();
};
// Goal is to call this
func(fn);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment