-
Hi, I wrote a simple pub/sub program in zenoh-cpp. Here's the relevant code segment of the subscriber: void runAsSubscriber(const char* conf_path) {
try {
auto config = zenoh::expect<zenoh::Config>(zenoh::config_from_file(conf_path));
auto session = zenoh::expect<zenoh::Session>(zenoh::open(std::move(config)));
auto subscriber = zenoh::expect<zenoh::Subscriber>(session.declare_subscriber(
"my/topic", messageHandler
));
std::getchar(); // I should put the function call here
} catch (const zenoh::ErrorMessage& ex) {
std::cerr << "Zenoh: " << ex.as_string_view() << std::endl;
exit(1);
}
std::getchar(); // If I put it here, the handler wouldn't get called
}
void messageHandler(const zenoh::Sample& sample) {
std::cout << "Received" << std::endl;
} Any ideas? Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @Alan-Kuan ! After leaving the try {} block both the void runAsSubscriber(const char* conf_path) {
zenoh::Session session(std::nullptr);
zenoh::Subscriber subscriber(std::nullptr);
try {
auto config = zenoh::expect<zenoh::Config>(zenoh::config_from_file(conf_path));
session = zenoh::expect<zenoh::Session>(zenoh::open(std::move(config)));
subscriber = zenoh::expect<zenoh::Subscriber>(session.declare_subscriber(
"my/topic", messageHandler
));
std::getchar(); // I should put the function call here
} catch (const zenoh::ErrorMessage& ex) {
std::cerr << "Zenoh: " << ex.as_string_view() << std::endl;
exit(1);
}
std::getchar(); // If I put it here, the handler wouldn't get called
}
void messageHandler(const zenoh::Sample& sample) {
std::cout << "Received" << std::endl;
} |
Beta Was this translation helpful? Give feedback.
Hi @Alan-Kuan !
After leaving the try {} block both the
session
andsubsriber
are automatically destroyed as they left the lexical scope. You may usestd::unique_ptr
or just declare unitializedsession
andsubscriber
outside the block, usingnull
constructors: