目标:学习创建和加载一个简单的插件使用pluginlib
背景
本教程来自于
http://wiki.ros.org/pluginlib and Writing and Using a Simple Plugin Tutorial.pluginlib是一个c++库,用于从ROS包中加载和卸载插件。插件是从运行库(即共享对象、动态链接库)加载的可动态加载类。使用pluginlib,不必将其应用程序与包含类的库显式链接——相反,pluginlib可以在任何时候打开包含导出类的库,而应用程序事先不知道该库或包含类定义的头文件。插件对于在不需要应用程序源代码的情况下扩展/修改应用程序行为非常有用。
任务
在本教程中,需要创建两个包,一个定义了基类,另一个提供插件。基类定义一个通用的多边形类,然后插件定义具体的形状。
1、创建基类包
ros2 pkg create --build-type ament_cmake polygon_base --dependencies pluginlib --node-name area_node
创建头文件:polygon_base/include/polygon_base/regular_polygon.hpp
里面内容如下:
#ifndef POLYGON_BASE_REGULAR_POLYGON_HPP #define POLYGON_BASE_REGULAR_POLYGON_HPP namespace polygon_base { class RegularPolygon { public: virtual void initialize(double side_length) = 0; virtual double area() = 0; virtual ~RegularPolygon(){} protected: RegularPolygon(){} }; } // namespace polygon_base #endif // POLYGON_BASE_REGULAR_POLYGON_HPP
为了让其他类可以使用这个头文件,在CMakeLists.txt中ament_target_dependencies命令之后编辑如下:
install( DIRECTORY include/ DESTINATION include )
在命令ament_package之前添加:
ament_export_include_directories(
include
)
2、创建一个插件包
ros2 pkg create --build-type ament_cmake polygon_plugins --dependencies polygon_base pluginlib --library-name polygon_plugins
2.1 source 代码为了插件
在文件/polygon_plugins/src/polygon_plugins.cpp中添加如下
#include <polygon_base/regular_polygon.hpp> #include <cmath> namespace polygon_plugins { class Square : public polygon_base::RegularPolygon { public: void initialize(double side_length) override { side_length_ = side_length; } double area() override { return side_length_ * side_length_; } protected: double side_length_; }; class Triangle : public polygon_base::RegularPolygon { public: void initialize(double side_length) override { side_length_ = side_length; } double area() override { return 0.5 * side_length_ * getHeight(); } double getHeight() { return sqrt((side_length_ * side_length_) - ((side_length_ / 2) * (side_length_ / 2))); } protected: double side_length_; }; } #include <pluginlib/class_list_macros.hpp> PLUGINLIB_EXPORT_CLASS(polygon_plugins::Square, polygon_base::RegularPolygon) PLUGINLIB_EXPORT_CLASS(polygon_plugins::Triangle, polygon_base::RegularPolygon)
上面实现了一个正方形和三角形,保存边,计算面积。最后三行说明了插件,会调用一些定义来注册实际的类为插件。
参数宏PLUGINLIB_EXPORT_CLASS:
1.插件类的完全类型:
polygon_plugins::Square
2.基类的完全类型:
polygon_base::RegularPolygon
2.2 插件声明XML
- libraries 插件 Beginner Client 10libraries插件beginner client libraries beginner接口client libraries beginner参数client libraries beginner文件client libraries beginner client libraries beginner client空间 libraries beginner client colcon prometheus library python client prometheus library client go libraries客户端beginner客户