Skip to content

Commit b9a1bf9

Browse files
committed
device: Add DEVICE_API macros
Add macro definitions for device drivers to instantiate API structs into iterable sections and to evaluate them. Signed-off-by: Pieter De Gendt <[email protected]>
1 parent b493b66 commit b9a1bf9

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

include/zephyr/device.h

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1195,8 +1195,47 @@ device_get_dt_nodelabels(const struct device *dev)
11951195

11961196
DT_FOREACH_STATUS_OKAY_NODE(Z_MAYBE_DEVICE_DECLARE_INTERNAL)
11971197

1198+
/** @brief Expands to the full type. */
1199+
#define Z_DEVICE_API_TYPE(_class) _CONCAT(_class, _driver_api)
1200+
11981201
/** @endcond */
11991202

1203+
/**
1204+
* @brief Wrapper macro for declaring device API structs inside iterable sections.
1205+
*
1206+
* @param _class The device API class.
1207+
* @param _name The API instance name.
1208+
*/
1209+
#define DEVICE_API(_class, _name) const STRUCT_SECTION_ITERABLE(Z_DEVICE_API_TYPE(_class), _name)
1210+
1211+
/**
1212+
* @brief Expands to the pointer of a device's API for a given class.
1213+
*
1214+
* @param _class The device API class.
1215+
* @param _dev The device instance pointer.
1216+
*
1217+
* @return the pointer to the device API.
1218+
*/
1219+
#define DEVICE_API_GET(_class, _dev) ((const struct Z_DEVICE_API_TYPE(_class) *)_dev->api)
1220+
1221+
/**
1222+
* @brief Macro that evaluates to a boolean that can be used to check if
1223+
* a device is of a particular class.
1224+
*
1225+
* @param _class The device API class.
1226+
* @param _dev The device instance pointer.
1227+
*
1228+
* @retval true If the device is of the given class
1229+
* @retval false If the device is not of the given class
1230+
*/
1231+
#define DEVICE_API_IS(_class, _dev) \
1232+
({ \
1233+
STRUCT_SECTION_START_EXTERN(Z_DEVICE_API_TYPE(_class)); \
1234+
STRUCT_SECTION_END_EXTERN(Z_DEVICE_API_TYPE(_class)); \
1235+
(DEVICE_API_GET(_class, _dev) < STRUCT_SECTION_END(Z_DEVICE_API_TYPE(_class)) && \
1236+
DEVICE_API_GET(_class, _dev) >= STRUCT_SECTION_START(Z_DEVICE_API_TYPE(_class))); \
1237+
})
1238+
12001239
#ifdef __cplusplus
12011240
}
12021241
#endif

0 commit comments

Comments
 (0)