add PyFfi impl

This commit is contained in:
llama 2025-11-01 22:23:35 +08:00
parent a882a87800
commit ec75658a0a
No known key found for this signature in database
GPG key ID: 0B7543854B9413C3

View file

@ -13,6 +13,7 @@ pub mod windows;
use std::path::PathBuf;
use anki_process::CommandExt;
use anyhow::ensure;
use anyhow::Context;
use anyhow::Result;
@ -153,3 +154,21 @@ struct PyFfi {
PyRun_SimpleString: PyRunSimpleString,
Py_FinalizeEx: PyFinalizeEx,
}
impl PyFfi {
fn run(self, preamble: impl AsRef<std::ffi::CStr>) -> Result<()> {
(self.Py_InitializeEx)(1);
let res = (self.Py_IsInitialized)();
ensure!(res != 0, "failed to initialise");
let res = (self.PyRun_SimpleString)(preamble.as_ref().as_ptr());
ensure!(res == 0, "failed to run preamble");
// test importing aqt first before falling back to usual launch
let res = (self.PyRun_SimpleString)(c"import aqt".as_ptr());
ensure!(res == 0, "failed to import aqt");
// from here on, don't fallback if we fail
let _ = (self.PyRun_SimpleString)(c"aqt.run()".as_ptr());
Ok(())
}
}