Skip to content

Commit 7f213fa

Browse files
author
Louis Beaudoin
committed
Document new senderPtr usage, change NULL to nullptr
1 parent 201862b commit 7f213fa

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

src/PacketSerial.h

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -340,14 +340,41 @@ class PacketSerial_
340340
///
341341
/// myPacketSerial.setPacketHandler(&onPacketReceived);
342342
///
343+
/// You can also register an arbitrary void* pointer to be passed to your packet handler method.
344+
/// This is most useful when PacketSerial is used inside a class, to pass a pointer to
345+
/// the containing class:
346+
///
347+
/// class EchoClass {
348+
/// public:
349+
/// void begin(unsigned long speed) {
350+
/// myPacketSerial.setPacketHandler(&onPacketReceived, this);
351+
/// myPacketSerial.begin(speed);
352+
/// }
353+
///
354+
/// // C-style callbacks can't use non-static methods,
355+
/// // so we use a static method that receives "this" as the sender argument:
356+
/// // https://wiki.c2.com/?VirtualStaticIdiom
357+
/// static void onPacketReceived(const void* sender, const uint8_t* buffer, size_t size) {
358+
/// ((EchoClass*)sender)->onPacketReceived(buffer, size);
359+
/// }
360+
///
361+
/// void onPacketReceived(const uint8_t* buffer, size_t size) {
362+
/// // we can now use myPacketSerial as needed here
363+
/// }
364+
///
365+
/// PacketSerial myPacketSerial;
366+
/// };
367+
///
343368
/// Setting a packet handler will remove all other packet handlers.
344369
///
345370
/// \param onPacketFunctionWithSender A pointer to the packet handler function.
346-
void setPacketHandler(PacketHandlerFunctionWithSender onPacketFunctionWithSender, void * senderPtr = NULL)
371+
/// \param senderPtr Optional pointer to a void* pointer, use default argument to send a pointer to the sending PacketSerial instance
372+
void setPacketHandler(PacketHandlerFunctionWithSender onPacketFunctionWithSender, void * senderPtr = nullptr)
347373
{
348374
_onPacketFunction = nullptr;
349375
_onPacketFunctionWithSender = onPacketFunctionWithSender;
350376
_senderPtr = senderPtr;
377+
// for backwards compatibility, the default _senderPtr is "this", but you can't use "this" as a default argument
351378
if(!senderPtr) _senderPtr = this;
352379
}
353380

0 commit comments

Comments
 (0)