You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用RPI Pico SDK:如何从重复定时器回调访问类私有成员?

在RPI Pico SDK定时器回调中访问自定义类私有成员的实现方法

要在Pico SDK的重复定时器回调中安全访问自定义类的私有成员,核心是利用SDK定时器API提供的user_data参数传递类实例指针,替代静态成员+友元的方案,既能保证封装性,又支持多实例独立工作。

修改后的完整代码示例

test.h

class MyClass {
private:
    int count; // 改为非静态私有成员,每个实例独立拥有
    struct repeating_timer main_loop_timer;
    // 静态成员回调,符合SDK的函数签名要求
    static bool main_loop_timer_callback(struct repeating_timer *t);
public:
    MyClass();
};

test.cc

#include <iostream>
#include "pico/stdlib.h"
#include "test.h"
using namespace std;

bool MyClass::main_loop_timer_callback(struct repeating_timer *t) {
    // 将user_data转换为当前MyClass实例指针
    MyClass* instance = static_cast<MyClass*>(t->user_data);
    // 直接访问实例的私有成员
    instance->count++;
    cout << "callback " << instance->count << endl;
    return true;
}

MyClass::MyClass() : count(0) {
    // 将当前实例指针作为user_data传入回调
    add_repeating_timer_us(-50000,
                           main_loop_timer_callback,
                           this,
                           &main_loop_timer);
}

test-main.cc

#include "pico/stdlib.h"
#include "test.h"
using namespace std;

int main() {
    stdio_init_all(); // 先初始化标准IO,确保输出正常
    MyClass test;
    while (true) { // 主循环维持程序运行
        sleep_ms(1000);
    }
}

关键修改说明

  1. 替换静态成员为实例成员:把原代码中的static int count改为非静态的int count,每个MyClass实例拥有独立的计数器,避免多实例数据冲突。
  2. 利用user_data传递实例指针:调用add_repeating_timer_us时,将this(当前类实例的指针)作为user_data参数传入,让回调函数能关联到具体实例。
  3. 静态成员回调函数:将回调声明为类的静态成员函数,既满足SDK对回调函数的签名要求(普通非静态成员函数隐含this指针,不符合SDK回调签名),又能通过转换后的实例指针访问私有成员。
  4. 修正主程序逻辑:先初始化标准IO再创建类实例,添加主循环防止程序直接退出,确保定时器回调能持续执行。

内容的提问来源于stack exchange,提问作者tomdean1939

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 16:55:17