Skip to content

Commit 73b2d43

Browse files
committed
fix: chip memory management
ensure that `Chip` instance is retained throughout the lifetime of the custom chip
1 parent 541a024 commit 73b2d43

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

src/lib.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ struct Chip {
2323
current_row: u32,
2424
}
2525

26+
// chipInit() will be called once per chip instance. We use CHIP_VEC to keep track of all the
27+
// instances, and use the user_data pointer to index into CHIP_VEC.
28+
static mut CHIP_VEC: Vec<Chip> = Vec::new();
29+
2630
fn draw_line(chip: &Chip, row: u32, color: u32) {
2731
let color_bytes_ptr = &color as *const u32 as *const u8;
2832

@@ -35,7 +39,7 @@ fn draw_line(chip: &Chip, row: u32, color: u32) {
3539
}
3640

3741
pub unsafe fn on_timer_fired(user_data: *const c_void) {
38-
let chip = &mut *(user_data as *mut Chip);
42+
let mut chip = &mut CHIP_VEC[user_data as usize];
3943

4044
if chip.current_row == 0 {
4145
debugPrint(CString::new("First row!").unwrap().into_raw());
@@ -65,9 +69,10 @@ pub unsafe extern "C" fn chipInit() {
6569
height,
6670
current_row: 0,
6771
};
72+
CHIP_VEC.push(chip);
6873

6974
let timer_config = TimerConfig {
70-
user_data: &chip as *const _ as *const c_void,
75+
user_data: (CHIP_VEC.len() - 1) as *const c_void,
7176
callback: on_timer_fired as *const c_void,
7277
};
7378

0 commit comments

Comments
 (0)