@@ -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