I am trying to communicate between applications with NATS.io. In order to asynchronously get a message when a publisher pushes something to a subject, you can do
|
natsConnection_Subscribe(&subscription, connection, subjectName, callback, closure);
|
The callback parameter is a `natsMsgHandler` which essentially is a
typedef void (*natsMsgHandler)(natsConnection *nc, natsSubscription *sub, natsMsg *msg, void *closure);
I have wrapped this logic in a class to hold the connection and subscription objects and added a wrapper method:
1 2 3 4 5 6
|
natsStatus adNatsSubAsyncWithCallback(const std::string& processName, const std::string& subName, lambda callback)
{
(...)
natsConnection_Subscribe(&sub->m_natsSubscription, nc, subName.c_str(), callback, nullptr);
(...)
}
|
Now, when I need to use this, let's say in my main, I can do:
1 2 3 4 5 6
|
nats_interface ni1;
ni1.adNatsSubAsyncWithCallback("onIdRequest", sendingSubj, [](natsConnection *nc,
natsSubscription *sub,
natsMsg *msg,
void *closure) { *DO STUFF* });
|
My problem is that I cannot for the love of god figure out how to best approach the scenario of having the callback be a method of a class.
Let's say I have a class
1 2 3 4 5 6 7
|
class test1
{
public:
void onIdRequest(natsConnection *nc, natsSubscription *sub, natsMsg *msg, void *closure) const {
natsMsg_Destroy(msg);
}
}
|
If I try something like
1 2 3 4 5 6 7 8
|
test1 t1;
auto temp = [t1](natsConnection *nc,
natsSubscription *sub,
natsMsg *msg,
void *closure) {
t1.onIdRequest(nc, sub, msg, closure);
};
|
and pass temp to the function call instead of a lambda directly, I get an error.
I also kind of tried to std::bind a method of class test1 with a matching definition to `natsMsgHandler` and pass that function<> object instead with absolutely catastrophic results.
How would I implement something like this?
EDIT:
The bind attempt was like this:
1 2
|
auto callback = std::bind(&test1::onIdRequest,&t1,_1,_2,_3,_4);
ni1.adNatsSubAsyncWithCallback("onIdRequest", sendingSubj, callback);
|