英文:
How do I access member variables from a repeating timer callback
问题
使用RPI Pico SDK,我有三个文件。
我想要使用回调函数并访问类的私有成员。
回调函数位于SDK中,我无法修改它。
我该如何做?
/////// test.h
bool main_loop_timer_callback(struct repeating_timer *t);
class MyClass {
private:
static int count;
struct repeating_timer main_loop_timer;
public:
MyClass();
friend bool main_loop_timer_callback(struct repeating_timer *t);
};
//////// test.cc
#include <iostream>
#include "pico/stdlib.h"
#include "test.h"
using namespace std;
bool main_loop_timer_callback(struct repeating_timer *t) {
MyClass::count++;
cout << "callback " << MyClass::count << endl;
return true;
}
MyClass::MyClass() {
add_repeating_timer_us(-50000,
main_loop_timer_callback,
NULL,
&main_loop_timer);
count = 0;
};
/////// test-main.cc
#include "pico/stdlib.h"
#include "test.h"
using namespace std;
int main() {
MyClass test;
stdio_init_all();
}
英文:
Using the RPI Pico SDK, I have three files.
I want to use a callback function and access private members of a class.
The callback function is in an SDK and I can not modify it.
How do I do this?
/////// test.h
bool main_loop_timer_callback(struct repeating_timer *t);
class MyClass {
private:
static int count;
struct repeating_timer main_loop_timer;
public:
MyClass();
friend bool main_loop_timer_callback(struct repeating_timer *t);
};
//////// test.cc
#include <iostream>
#include "pico/stdlib.h"
#include "test.h"
using namespace std;
bool main_loop_timer_callback(struct repeating_timer *t) {
MyClass::count++;
cout << "callback " << MyClass::count << endl;
return true;
}
MyClass::MyClass() {
add_repeating_timer_us(-50000,
main_loop_timer_callback,
NULL,
&main_loop_timer);
count = 0;
};
/////// test-main.cc
#include "pico/stdlib.h"
#include "test.h"
using namespace std;
int main() {
MyClass test;
stdio_init_all();
}
答案1
得分: 1
Pico Pico repeating_timer
API 允许您在添加定时器时传递一个 user_data
参数(传递给 add_repeating_timer_us
的第三个参数)。
该值稍后将在传递到回调函数的 struct repeating_timer
的 user_data
成员中返回。
这可以是您想要的任何内容,例如在您的情况下,一个指向 MyClass
的指针,只要您将其转换为 void *
类型。
英文:
The Pi Pico repeating_timer
API allows you to pass a user_data
argument when adding a timer (the third parameter to add_repeating_timer_us
).
This value is later returned in the user_data
member of the struct repeating_timer
passed to your callback.
This can be anything you want, e.g. in your case, a pointer to MyClass
, so long as you cast it to and from void *
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论