Skip to content

Instantly share code, notes, and snippets.

@Pikachuxxxx
Last active May 18, 2025 11:19
Show Gist options
  • Save Pikachuxxxx/f0ffddd37a3bf07d1d65b3acbb87b117 to your computer and use it in GitHub Desktop.
Save Pikachuxxxx/f0ffddd37a3bf07d1d65b3acbb87b117 to your computer and use it in GitHub Desktop.
Based on an Insomniac's Engine programmer's blog, this is a trick I learned from him.
#include <iostream>
#include <utility>
void callback_test(void* userdata, void* path) {
std::cout << "Callback function called with path: "
<< static_cast<const char*>(path)
<< " and userdata: "
<< static_cast<const char*>(userdata) << std::endl;
}
typedef void (*ResourceLoadCB) (void*, void*);
struct LoadDesc
{
const char* path;
void* userdata;
ResourceLoadCB callback;
};
// Function to load a resource
bool load_resource(LoadDesc* loaddesc) {
if (loaddesc->path != nullptr) {
loaddesc->callback(loaddesc->userdata, (void*)loaddesc->path);
return true; // Indicate successful execution
}
return false; // Indicate failure
}
template <typename Fn>
bool load_resource(LoadDesc* loaddesc, Fn func) {
auto closure = [](void* userdata, void* path) {
// cast the Fn from userdata
Fn* funcPtrToLambda = static_cast<Fn*>(userdata);
// userdata of the Fn is implicit we call this function as a deferred call inside another lambda that mathced our signature
(*funcPtrToLambda)(path);
};
loaddesc->userdata = &func;
loaddesc->callback = closure;
return load_resource(loaddesc);
}
int main() {
LoadDesc desc;
desc.path = "/path/to/";
desc.userdata = (void*)"filename.txt";
desc.callback = callback_test;
// Pass the address of `desc` to `load_resource`
if (load_resource(&desc)) {
std::cout << "Resource loaded successfully." << std::endl;
} else {
std::cout << "Failed to load resource." << std::endl;
}
// Exampele 2: using lambda
const char* new_ext = "buffer.asset";
auto loadCB = [new_ext](void* path) {
std::cout << "Lambda Callback function called with path: "
<< static_cast<const char*>(path)
<< " and userdata: "
<< static_cast<const char*>(new_ext) << std::endl;
};
LoadDesc loadcbDesc;
loadcbDesc.path = "path/to/CB/";
if (load_resource(&loadcbDesc, loadCB)) {
std::cout << "Resource loaded successfully." << std::endl;
} else {
std::cout << "Failed to load resource." << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment