nbind
nbind copied to clipboard
Store nbind::cbFunction as class member
I have a callback function that prints output to the user running in node, and it's something that is used a lot by a class in c++. I want to pass this function as an argument to the constructor of the c++ class, so that it can be called from c++ without me having to repeatedly pass it to all the functions that need to use it. I've tried to declare a private member nbind::cbFunction, but the compiler tells me that it's been implicity deleted. I'm guessing that this has to do with me not specificlaly defining the typedef in the operator overload. Is this even possible to do? or am I wasting time.
std::unique_ptr helps here. Fully working example adapted from #52:
#include "nbind/api.h"
/* If using C++11 instead of C++14, uncomment this:
namespace std {
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
}
*/
class Test {
public:
Test(nbind::cbFunction cb) {
fn = std::make_unique<nbind::cbFunction>(cb);
}
void frob() {
(*fn)();
}
std::unique_ptr<nbind::cbFunction> fn;
};
#include "nbind/nbind.h"
NBIND_CLASS(Test) {
construct<nbind::cbFunction>();
method(frob);
}
JS:
var nbind = require('nbind');
var lib = nbind.init().lib;
new lib.Test(() => console.log('Hello, World!')).frob();
This seem to prevent Test class wrapper to be garbage collected. How can I release the fn pointer?
@parro-it That was hopefully fixed in this commit: https://github.com/charto/nbind/commit/07aa65c0d61ef27cd17b48cccf6607e6630419c8
You can call the cbFunction's (it's a cbWrapper<void>) reset method to release the pointer from C++ side.
Thank you! I will try it later.