Skip to content

Commit cd95d06

Browse files
jeplerpetterreinholdtsen
authored andcommitted
hal_priv: Type-safe C++ for access to HAL shared memory area
Signed-off-by: Jeff Epler <jepler@unpythonic.net>
1 parent 0276824 commit cd95d06

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

src/hal/hal_priv.h

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,47 @@ extern char *hal_shmem_base;
135135
extern struct hal_data_t *hal_data;
136136
RTAPI_END_DECLS
137137

138+
#ifdef __cplusplus
139+
template<class T>
140+
bool hal_shmchk(T *t) {
141+
char *c = (char*)t;
142+
return c > hal_shmem_base && c < hal_shmem_base + HAL_SIZE;
143+
}
144+
145+
template<class T>
146+
int hal_shmoff(T *t) { return t ? (char*)t - hal_shmem_base : 0; }
147+
148+
template<class T>
149+
T *hal_shmptr(int p) { return p ? (T*)(hal_shmem_base + p) : nullptr; }
150+
151+
template<class T>
152+
class hal_shmfield {
153+
public:
154+
hal_shmfield() : off{} {}
155+
hal_shmfield(T *t) : off{hal_shmoff(t)} {}
156+
hal_shmfield &operator=(T *t) { off = hal_shmoff(t); }
157+
T *get() { return hal_shmptr<T>(off); }
158+
const T *get() const { return hal_shmptr<T>(off); }
159+
T *operator *() { return get(); }
160+
const T *operator *() const { return get(); }
161+
T *operator ->() { return get(); }
162+
const T *operator ->() const { return get(); }
163+
operator bool() const { return off; }
164+
private:
165+
int off;
166+
};
167+
168+
template<class T>
169+
hal_shmfield<T> hal_make_shmfield(T *t) {
170+
return hal_shmfield<T>(t);
171+
}
172+
173+
static_assert(sizeof(hal_shmfield<void>) == sizeof(int), "hal_shmfield size matches");
138174

175+
#define SHMFIELD(type) hal_shmfield<type>
176+
#define SHMPTR(arg) ((arg).get())
177+
#define SHMOFF(ptr) (hal_make_shmfield(ptr))
178+
#else
139179
#define SHMFIELD(type) int
140180

141181
/* SHMPTR(offset) converts 'offset' to a void pointer. */
@@ -151,6 +191,7 @@ RTAPI_END_DECLS
151191
false by design */
152192
#define SHMCHK(ptr) ( ((char *)(ptr)) > (hal_shmem_base) && \
153193
((char *)(ptr)) < (hal_shmem_base + HAL_SIZE) )
194+
#endif
154195

155196
/** The good news is that none of this linked list complexity is
156197
visible to the components that use this API. Complexity here

0 commit comments

Comments
 (0)