Adding comments above from AndyZe, yes you need to get the node pointer and pass it to another class. But if you do this in the class constructor, a bad_weak_ptr
error will always show up. You can prevent this by initiating the class in callback.
I'm gonna use ClassA and ClassB example above, say you want to extend the node to ClassB to use ClassB functions from ClassA. Here's the header code of ClassB:
class ClassB {
public:
ClassB(rclcpp::Node::SharedPtr node); // constructor
// your code here
private:
rclcpp::Node::SharedPtr node_;
// your code here
and here's the definition code of ClassB:
// constructor
ClassB::ClassB(rclcpp::Node::SharedPtr node) : node_(node) {
// your code here
}
Then in ClassA file:
class ClassA : public rclcpp::Node {
public:
ClassA() : Node("class_a") {
// your code here
// use one-time timer to initiate class B
timer = this->create_wall_timer(500ms, std::bind(&ClassA::initialization, this));
}
private:
rclcpp::TimerBase::SharedPtr timer;
std::shared_ptr<ClassB> class_b;
void initialization() {
// get node pointer, pass into Class B
class_b = std::make_shared<ClassB>(shared_from_this());
// replace timer with loop callback after initialization finished
timer = this->create_wall_timer(500ms, std::bind(&UsingLibCpp::timer_callback, this));
}
void timer_callback() {
// your code here
// use Class B function
class_b->class_b_function();
}
I finally got it work after 2 weeks of digging. Too bad ROS2 documentation is still lacking in program style like this. Hope it helps