Skip to content

Commit 6ffcc98

Browse files
authored
Merge pull request #17 from AzureMarker/fix/console-drop
Add back Console::drop
2 parents e4b2e70 + c3ae3a1 commit 6ffcc98

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

ctru-rs/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ name = "ctru"
1212

1313
[dependencies]
1414
ctru-sys = { path = "../ctru-sys", version = "0.4" }
15+
const-zero = "0.1.0"
1516
linker-fix-3ds = { git = "https://github.com/Meziu/rust-linker-fix-3ds.git" }
1617
pthread-3ds = { git = "https://github.com/Meziu/pthread-3ds.git" }
1718
libc = { git = "https://github.com/Meziu/libc.git" }

ctru-rs/src/console.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,31 @@ impl Default for Console {
5050
Console::init(Screen::Top)
5151
}
5252
}
53+
54+
impl Drop for Console {
55+
fn drop(&mut self) {
56+
static mut EMPTY_CONSOLE: PrintConsole = unsafe { const_zero::const_zero!(PrintConsole) };
57+
58+
unsafe {
59+
// Safety: We are about to deallocate the PrintConsole data pointed
60+
// to by libctru. Without this drop code libctru would have a
61+
// dangling pointer that it writes to on every print. To prevent
62+
// this we replace the console with an empty one if it was selected.
63+
// This is the same state that libctru starts up in, before
64+
// initializing a console. Writes to the console will not show up on
65+
// the screen, but it won't crash either.
66+
67+
// Get the current console by replacing it with an empty one.
68+
let current_console = ctru_sys::consoleSelect(&mut EMPTY_CONSOLE);
69+
70+
if std::ptr::eq(current_console, &*self.context) {
71+
// Console dropped while selected. We just replaced it with the
72+
// empty console so nothing more to do.
73+
} else {
74+
// Console dropped while a different console was selected. Put back
75+
// the console that was selected.
76+
ctru_sys::consoleSelect(current_console);
77+
}
78+
}
79+
}
80+
}

0 commit comments

Comments
 (0)