1use std::ffi::{c_char, c_void, CStr};
2use std::fmt::{self, Display, Write as _};
3use std::mem::{offset_of, size_of};
4use std::path::PathBuf;
5use std::ptr::{self, NonNull};
6use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering};
7
8use crate::change::{Change, FunctionHook, PointerSwap};
9use crate::cpu::Cpu;
10use crate::error::{check, Result};
11use crate::event::{Event, Payload};
12use crate::fnptr::{FnPtr, FnSymbol};
13use crate::panic::{catch_raw, resume, run_callback};
14use crate::sys::{
15 AnvilChange, AnvilCpuCallback, AnvilCpuContext, AnvilHost, AnvilLogLevel, AnvilPlugin,
16 AnvilResult, AnvilSetting, AnvilSymbol, ANVIL_LOG_DEBUG, ANVIL_LOG_ERROR, ANVIL_LOG_INFO,
17 ANVIL_LOG_WARNING,
18};
19use crate::table::Table;
20use crate::text::{c_string, owned_string, static_str};
21
22static TABLE: AtomicPtr<AnvilHost> = AtomicPtr::new(ptr::null_mut());
23static PLUGIN: AtomicPtr<AnvilPlugin> = AtomicPtr::new(ptr::null_mut());
24
25pub(crate) fn covers_api_2_0(table: Table<AnvilHost>) -> bool {
27 table.size() as usize
28 >= offset_of!(AnvilHost, publish) + size_of::<Option<unsafe extern "C" fn()>>()
29}
30
31pub(crate) fn install(table: Table<AnvilHost>, plugin: *mut AnvilPlugin) {
34 PLUGIN.store(plugin, Ordering::Release);
35 TABLE.store(table.as_ptr().cast_mut(), Ordering::Release);
36}
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
40pub enum LogLevel {
41 Debug,
43 Info,
45 Warning,
47 Error,
49}
50
51impl LogLevel {
52 const fn raw(self) -> AnvilLogLevel {
53 match self {
54 Self::Debug => ANVIL_LOG_DEBUG,
55 Self::Info => ANVIL_LOG_INFO,
56 Self::Warning => ANVIL_LOG_WARNING,
57 Self::Error => ANVIL_LOG_ERROR,
58 }
59 }
60}
61
62#[derive(Clone, Copy, Debug)]
64pub struct GameInfo {
65 pub build_id: Option<&'static str>,
67 pub image_base: usize,
69 pub image_size: u32,
71 pub sha256: Option<&'static str>,
74}
75
76#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
79pub struct Key(pub i64);
80
81impl Key {
82 pub const SHIFT: i64 = 0x100;
84 pub const CTRL: i64 = 0x200;
86 pub const ALT: i64 = 0x400;
88
89 pub const fn vk(self) -> u8 {
91 (self.0 & 0xFF) as u8
92 }
93 pub const fn shift(self) -> bool {
95 self.0 & Self::SHIFT != 0
96 }
97 pub const fn ctrl(self) -> bool {
99 self.0 & Self::CTRL != 0
100 }
101 pub const fn alt(self) -> bool {
103 self.0 & Self::ALT != 0
104 }
105 pub const fn is_bound(self) -> bool {
107 self.0 != 0
108 }
109}
110
111#[derive(Clone, Copy)]
118pub struct Host {
119 table: Table<AnvilHost>,
120 plugin: *mut AnvilPlugin,
121}
122
123unsafe impl Send for Host {}
125unsafe impl Sync for Host {}
127
128impl fmt::Debug for Host {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 f.debug_struct("Host")
131 .field("anvil_version", &self.anvil_version())
132 .finish_non_exhaustive()
133 }
134}
135
136struct CpuAdapter<F> {
139 callback: F,
140 what: String,
141 panicked: AtomicBool,
142}
143
144unsafe extern "C" fn cpu_adapter<F: Fn(&mut Cpu) + Send + Sync + 'static>(
145 cpu: *mut AnvilCpuContext,
146 user: *mut c_void,
147) {
148 let adapter = unsafe { &*user.cast::<CpuAdapter<F>>() };
150 let Some(cpu) = (unsafe { Cpu::from_raw(cpu) }) else {
152 return;
153 };
154 run_callback(&adapter.what, &adapter.panicked, (), || {
155 (adapter.callback)(cpu)
156 });
157}
158
159struct EventAdapter<P, F> {
160 handler: F,
161 what: String,
162 panicked: AtomicBool,
163 _payload: std::marker::PhantomData<fn() -> P>,
164}
165
166unsafe extern "C" fn event_adapter<P: Payload, F: Fn(&P) + Send + Sync + 'static>(
167 _event: *const c_char,
168 payload: *const c_void,
169 context: *mut c_void,
170) {
171 let adapter = unsafe { &*context.cast::<EventAdapter<P, F>>() };
173 run_callback(&adapter.what, &adapter.panicked, (), || {
174 if let Some(payload) = unsafe { P::read(payload) } {
176 (adapter.handler)(&payload);
177 }
178 });
179}
180
181struct RawEventAdapter<F> {
182 handler: F,
183 what: String,
184 panicked: AtomicBool,
185}
186
187unsafe extern "C" fn raw_event_adapter<F: Fn(&str, *const c_void) + Send + Sync + 'static>(
188 event: *const c_char,
189 payload: *const c_void,
190 context: *mut c_void,
191) {
192 let adapter = unsafe { &*context.cast::<RawEventAdapter<F>>() };
194 run_callback(&adapter.what, &adapter.panicked, (), || {
195 let name = unsafe { owned_string(event) };
197 (adapter.handler)(&name, payload);
198 });
199}
200
201struct SettingAdapter<F> {
202 handler: F,
203 what: String,
204 panicked: AtomicBool,
205}
206
207unsafe extern "C" fn setting_adapter<F: Fn() + Send + Sync + 'static>(
208 _setting: AnvilSetting,
209 context: *mut c_void,
210) {
211 let adapter = unsafe { &*context.cast::<SettingAdapter<F>>() };
213 run_callback(&adapter.what, &adapter.panicked, (), || (adapter.handler)());
214}
215
216fn write_log(
218 table: Table<AnvilHost>,
219 plugin: *mut AnvilPlugin,
220 level: LogLevel,
221 message: &dyn Display,
222) {
223 let Some(log) = field!(table, AnvilHost, log).flatten() else {
224 return;
225 };
226 let mut text = String::new();
227 if write!(text, "{message}").is_err() {
228 text = "(a log line could not be formatted)".to_owned();
229 }
230 let text = c_string(&text);
231 unsafe { log(plugin, level.raw(), text.as_ptr()) };
233}
234
235pub(crate) fn wide_path(text: *const u16) -> PathBuf {
236 if text.is_null() {
237 return PathBuf::new();
238 }
239 let units = unsafe {
241 let mut length = 0;
242 while *text.add(length) != 0 {
243 length += 1;
244 }
245 std::slice::from_raw_parts(text, length)
246 };
247 #[cfg(windows)]
248 {
249 use std::os::windows::ffi::OsStringExt;
250 PathBuf::from(std::ffi::OsString::from_wide(units))
251 }
252 #[cfg(not(windows))]
253 {
254 PathBuf::from(String::from_utf16_lossy(units))
255 }
256}
257
258impl Host {
259 pub(crate) fn from_parts(table: Table<AnvilHost>, plugin: *mut AnvilPlugin) -> Self {
260 Self { table, plugin }
261 }
262
263 pub fn current() -> Option<Self> {
265 let table = TABLE.load(Ordering::Acquire);
266 let plugin = PLUGIN.load(Ordering::Acquire);
267 unsafe { Table::from_raw(table) }.map(|table| Self { table, plugin })
269 }
270
271 pub fn c_api(&self) -> Table<AnvilHost> {
273 self.table
274 }
275
276 pub fn raw_plugin(&self) -> *mut AnvilPlugin {
278 self.plugin
279 }
280
281 pub fn module(&self, name: &str) -> Result<Host> {
296 let module = function!(self.table, AnvilHost, module)?;
297 let text = c_string(name);
298 let mut out: *mut AnvilPlugin = ptr::null_mut();
299 let result = unsafe { module(self.plugin, text.as_ptr(), &mut out) };
302 check(result, || format!("module {name}"))?;
303 Ok(Self {
304 table: self.table,
305 plugin: out,
306 })
307 }
308
309 pub fn anvil_version(&self) -> &'static str {
311 let version = field!(self.table, AnvilHost, anvil_version).unwrap_or(ptr::null());
312 unsafe { static_str(version) }.unwrap_or("")
314 }
315
316 pub fn game(&self) -> GameInfo {
318 let game = field!(self.table, AnvilHost, game).unwrap_or(ptr::null());
319 if game.is_null() {
320 return GameInfo {
321 build_id: None,
322 image_base: 0,
323 image_size: 0,
324 sha256: None,
325 };
326 }
327 let sha256 = unsafe {
332 AtomicPtr::from_ptr(
333 ptr::addr_of!((*game).sha256)
334 .cast_mut()
335 .cast::<*mut c_char>(),
336 )
337 .load(Ordering::Acquire)
338 };
339 let (build_id, image_base, image_size) =
341 unsafe { ((*game).build_id, (*game).image_base, (*game).image_size) };
342 GameInfo {
343 build_id: unsafe { static_str(build_id) },
345 image_base,
346 image_size,
347 sha256: unsafe { static_str(sha256.cast_const()) },
349 }
350 }
351
352 pub fn plugin_dir(&self) -> PathBuf {
354 field!(self.table, AnvilHost, plugin_dir)
356 .flatten()
357 .map_or_else(PathBuf::new, |f| wide_path(unsafe { f(self.plugin) }))
358 }
359
360 pub fn data_dir(&self) -> PathBuf {
362 field!(self.table, AnvilHost, data_dir)
364 .flatten()
365 .map_or_else(PathBuf::new, |f| wide_path(unsafe { f(self.plugin) }))
366 }
367
368 pub fn log(&self, level: LogLevel, message: impl Display) {
373 write_log(self.table, self.plugin, level, &message);
374 }
375
376 pub fn debug(&self, message: impl Display) {
378 self.log(LogLevel::Debug, message);
379 }
380
381 pub fn info(&self, message: impl Display) {
383 self.log(LogLevel::Info, message);
384 }
385
386 pub fn warn(&self, message: impl Display) {
388 self.log(LogLevel::Warning, message);
389 }
390
391 pub fn error(&self, message: impl Display) {
393 self.log(LogLevel::Error, message);
394 }
395
396 pub unsafe fn hook<F: FnPtr>(
414 &self,
415 hook: &'static FunctionHook<F>,
416 symbol: AnvilSymbol,
417 detour: F,
418 ) -> Result<()> {
419 let claim = hook.claim("hook_function")?;
420 let call = function!(self.table, AnvilHost, hook_function)?;
421 let mut change: *mut AnvilChange = ptr::null_mut();
422 let mut next: *mut c_void = ptr::null_mut();
423 let cell = hook.next_cell(&mut next);
424 let result = unsafe { call(self.plugin, symbol, detour.into_raw(), cell, &mut change) };
427 check(result, || format!("hook_function symbol {symbol}"))?;
428 hook.finish(claim, cell, next, change);
429 Ok(())
430 }
431
432 pub fn hook_symbol<F: FnPtr>(
442 &self,
443 hook: &'static FunctionHook<F>,
444 symbol: FnSymbol<F>,
445 detour: F,
446 ) -> Result<()> {
447 unsafe { self.hook(hook, symbol.id(), detour) }
450 }
451
452 pub fn mid_hook<F>(&self, site: AnvilSymbol, callback: F) -> Result<Change>
457 where
458 F: Fn(&mut Cpu) + Send + Sync + 'static,
459 {
460 let call = function!(self.table, AnvilHost, mid_hook)?;
461 let what = format!("mid_hook symbol {site}");
462 self.cpu_change(what, callback, |function, user, out| {
463 unsafe { call(self.plugin, site, function, user, out) }
465 })
466 }
467
468 pub fn replace_block<F>(&self, block: AnvilSymbol, callback: F) -> Result<Change>
472 where
473 F: Fn(&mut Cpu) + Send + Sync + 'static,
474 {
475 let call = function!(self.table, AnvilHost, replace_block)?;
476 let what = format!("replace_block symbol {block}");
477 self.cpu_change(what, callback, |function, user, out| {
478 unsafe { call(self.plugin, block, function, user, out) }
480 })
481 }
482
483 pub unsafe fn redirect_call<F: FnPtr>(
490 &self,
491 hook: &'static FunctionHook<F>,
492 call_site: AnvilSymbol,
493 target: F,
494 ) -> Result<()> {
495 let claim = hook.claim("redirect_call")?;
496 let call = function!(self.table, AnvilHost, redirect_call)?;
497 let mut change: *mut AnvilChange = ptr::null_mut();
498 let mut next: *mut c_void = ptr::null_mut();
499 let cell = hook.next_cell(&mut next);
500 let result = unsafe { call(self.plugin, call_site, target.into_raw(), cell, &mut change) };
502 check(result, || format!("redirect_call symbol {call_site}"))?;
503 hook.finish(claim, cell, next, change);
504 Ok(())
505 }
506
507 pub unsafe fn patch_bytes(&self, site: AnvilSymbol, bytes: &[u8]) -> Result<Change> {
513 let call = function!(self.table, AnvilHost, patch_bytes)?;
514 let mut change: *mut AnvilChange = ptr::null_mut();
515 let result = unsafe {
517 call(
518 self.plugin,
519 site,
520 bytes.as_ptr().cast(),
521 bytes.len(),
522 &mut change,
523 )
524 };
525 check(result, || format!("patch_bytes symbol {site}"))?;
526 Ok(Change::from_raw(change))
527 }
528
529 pub unsafe fn swap_pointer(
537 &self,
538 swap: &'static PointerSwap,
539 slot: AnvilSymbol,
540 value: *mut c_void,
541 ) -> Result<()> {
542 let claim = swap.claim()?;
543 let call = function!(self.table, AnvilHost, swap_pointer)?;
544 let mut change: *mut AnvilChange = ptr::null_mut();
545 let result = unsafe { call(self.plugin, slot, value, swap.previous_slot(), &mut change) };
547 check(result, || format!("swap_pointer symbol {slot}"))?;
548 claim.finish(change);
549 Ok(())
550 }
551
552 pub unsafe fn replace_import<F: FnPtr>(
558 &self,
559 hook: &'static FunctionHook<F>,
560 module: &str,
561 function: &str,
562 replacement: F,
563 ) -> Result<()> {
564 let claim = hook.claim("replace_import")?;
565 let call = function!(self.table, AnvilHost, replace_import)?;
566 let (module_c, function_c) = (c_string(module), c_string(function));
567 let mut change: *mut AnvilChange = ptr::null_mut();
568 let mut next: *mut c_void = ptr::null_mut();
569 let cell = hook.next_cell(&mut next);
570 let result = unsafe {
572 call(
573 self.plugin,
574 module_c.as_ptr(),
575 function_c.as_ptr(),
576 replacement.into_raw(),
577 cell,
578 &mut change,
579 )
580 };
581 check(result, || format!("replace_import {module}!{function}"))?;
582 hook.finish(claim, cell, next, change);
583 Ok(())
584 }
585
586 pub unsafe fn hook_at<F: FnPtr>(
593 &self,
594 hook: &'static FunctionHook<F>,
595 address: NonNull<c_void>,
596 expected_prologue: &[u8],
597 detour: F,
598 ) -> Result<()> {
599 let claim = hook.claim("hook_function_at")?;
600 let call = function!(self.table, AnvilHost, hook_function_at)?;
601 let mut change: *mut AnvilChange = ptr::null_mut();
602 let mut next: *mut c_void = ptr::null_mut();
603 let cell = hook.next_cell(&mut next);
604 let result = unsafe {
606 call(
607 self.plugin,
608 address.as_ptr(),
609 bytes_or_null(expected_prologue),
610 expected_prologue.len(),
611 detour.into_raw(),
612 cell,
613 &mut change,
614 )
615 };
616 check(result, || {
617 format!("hook_function_at {:p}", address.as_ptr())
618 })?;
619 hook.finish(claim, cell, next, change);
620 Ok(())
621 }
622
623 pub unsafe fn mid_hook_at<F>(
629 &self,
630 address: NonNull<c_void>,
631 expected: &[u8],
632 callback: F,
633 ) -> Result<Change>
634 where
635 F: Fn(&mut Cpu) + Send + Sync + 'static,
636 {
637 let call = function!(self.table, AnvilHost, mid_hook_at)?;
638 let what = format!("mid_hook_at {:p}", address.as_ptr());
639 self.cpu_change(what, callback, |function, user, out| {
640 unsafe {
642 call(
643 self.plugin,
644 address.as_ptr(),
645 bytes_or_null(expected),
646 expected.len(),
647 function,
648 user,
649 out,
650 )
651 }
652 })
653 }
654
655 pub fn group<R>(&self, body: impl FnOnce() -> Result<R>) -> Result<R> {
672 let begin = function!(self.table, AnvilHost, begin_group)?;
673 let commit = function!(self.table, AnvilHost, commit_group)?;
674 let abort = function!(self.table, AnvilHost, abort_group)?;
675 check(unsafe { begin(self.plugin) }, || "begin_group")?;
677 crate::change::group_opened();
678 match catch_raw(body) {
679 Ok(Ok(value)) => {
680 let committed = check(unsafe { commit(self.plugin) }, || "commit_group");
682 crate::change::group_closed(committed.is_err());
683 committed?;
684 Ok(value)
685 }
686 Ok(Err(error)) => {
687 unsafe { abort(self.plugin) };
689 crate::change::group_closed(true);
690 Err(error)
691 }
692 Err(panic) => {
693 unsafe { abort(self.plugin) };
695 crate::change::group_closed(true);
696 resume(panic)
698 }
699 }
700 }
701
702 fn cpu_change<F>(
703 &self,
704 what: String,
705 callback: F,
706 request: impl FnOnce(AnvilCpuCallback, *mut c_void, *mut *mut AnvilChange) -> AnvilResult,
707 ) -> Result<Change>
708 where
709 F: Fn(&mut Cpu) + Send + Sync + 'static,
710 {
711 let adapter: &'static CpuAdapter<F> = Box::leak(Box::new(CpuAdapter {
712 callback,
713 what,
714 panicked: AtomicBool::new(false),
715 }));
716 let mut change: *mut AnvilChange = ptr::null_mut();
717 let result = request(
718 Some(cpu_adapter::<F>),
719 ptr::from_ref(adapter).cast_mut().cast(),
720 &mut change,
721 );
722 check(result, || adapter.what.clone())?;
723 Ok(Change::from_raw(change))
724 }
725
726 pub fn address(&self, symbol: AnvilSymbol) -> Option<NonNull<c_void>> {
731 field!(self.table, AnvilHost, address_of)
733 .flatten()
734 .and_then(|f| NonNull::new(unsafe { f(self.plugin, symbol) }))
735 }
736
737 pub fn present(&self, symbol: AnvilSymbol) -> bool {
740 self.address(symbol).is_some()
741 }
742
743 pub unsafe fn function<F: FnPtr>(&self, symbol: AnvilSymbol) -> Option<F> {
748 self.address(symbol)
750 .map(|address| unsafe { F::from_raw(address.as_ptr()) })
751 }
752
753 pub unsafe fn data<T>(&self, symbol: AnvilSymbol) -> Option<&'static T> {
760 self.address(symbol)
762 .map(|address| unsafe { address.cast::<T>().as_ref() })
763 }
764
765 pub fn value(&self, symbol: AnvilSymbol, name: &str) -> Result<u64> {
767 let call = function!(self.table, AnvilHost, symbol_value)?;
768 let name_c = c_string(name);
769 let mut out = 0u64;
770 let result = unsafe { call(self.plugin, symbol, name_c.as_ptr(), &mut out) };
772 check(result, || format!("symbol_value symbol {symbol}.{name}"))?;
773 Ok(out)
774 }
775
776 pub fn setting_bool(&self, setting: AnvilSetting) -> bool {
780 field!(self.table, AnvilHost, setting_bool)
782 .flatten()
783 .is_some_and(|f| unsafe { f(self.plugin, setting) } != 0)
784 }
785
786 pub fn setting_int(&self, setting: AnvilSetting) -> i64 {
788 field!(self.table, AnvilHost, setting_int)
790 .flatten()
791 .map_or(0, |f| unsafe { f(self.plugin, setting) })
792 }
793
794 pub fn setting_float(&self, setting: AnvilSetting) -> f64 {
796 field!(self.table, AnvilHost, setting_float)
798 .flatten()
799 .map_or(0.0, |f| unsafe { f(self.plugin, setting) })
800 }
801
802 pub fn setting_string(&self, setting: AnvilSetting) -> String {
804 field!(self.table, AnvilHost, setting_string)
806 .flatten()
807 .map_or_else(String::new, |f| unsafe {
808 owned_string(f(self.plugin, setting))
809 })
810 }
811
812 pub fn setting_key(&self, setting: AnvilSetting) -> Key {
814 Key(self.setting_int(setting))
815 }
816
817 pub fn subscribe_setting<F>(&self, setting: AnvilSetting, handler: F) -> Result<()>
820 where
821 F: Fn() + Send + Sync + 'static,
822 {
823 let call = function!(self.table, AnvilHost, subscribe_setting)?;
824 let what = format!("setting {setting} handler");
825 let adapter: &'static SettingAdapter<F> = Box::leak(Box::new(SettingAdapter {
826 handler,
827 what,
828 panicked: AtomicBool::new(false),
829 }));
830 let result = unsafe {
832 call(
833 self.plugin,
834 setting,
835 Some(setting_adapter::<F>),
836 ptr::from_ref(adapter).cast_mut().cast(),
837 )
838 };
839 check(result, || format!("subscribe_setting setting {setting}"))
840 }
841
842 pub fn subscribe<P, F>(&self, event: Event<P>, handler: F) -> Result<()>
847 where
848 P: Payload,
849 F: Fn(&P) + Send + Sync + 'static,
850 {
851 let call = function!(self.table, AnvilHost, subscribe)?;
852 let name = event.name();
853 let what = format!("{} handler", name.to_string_lossy());
854 let adapter: &'static EventAdapter<P, F> = Box::leak(Box::new(EventAdapter {
855 handler,
856 what,
857 panicked: AtomicBool::new(false),
858 _payload: std::marker::PhantomData,
859 }));
860 let result = unsafe {
862 call(
863 self.plugin,
864 name.as_ptr(),
865 Some(event_adapter::<P, F>),
866 ptr::from_ref(adapter).cast_mut().cast(),
867 )
868 };
869 check(result, || format!("subscribe {}", name.to_string_lossy()))
870 }
871
872 pub fn subscribe_raw<F>(&self, event: &str, handler: F) -> Result<()>
875 where
876 F: Fn(&str, *const c_void) + Send + Sync + 'static,
877 {
878 let call = function!(self.table, AnvilHost, subscribe)?;
879 let name = c_string(event);
880 let what = format!("{event} handler");
881 let adapter: &'static RawEventAdapter<F> = Box::leak(Box::new(RawEventAdapter {
882 handler,
883 what,
884 panicked: AtomicBool::new(false),
885 }));
886 let result = unsafe {
888 call(
889 self.plugin,
890 name.as_ptr(),
891 Some(raw_event_adapter::<F>),
892 ptr::from_ref(adapter).cast_mut().cast(),
893 )
894 };
895 check(result, || format!("subscribe {event}"))
896 }
897
898 pub fn publish(&self, event: &str) -> Result<()> {
901 unsafe { self.publish_raw(event, ptr::null()) }
903 }
904
905 pub unsafe fn publish_raw(&self, event: &str, payload: *const c_void) -> Result<()> {
916 let call = function!(self.table, AnvilHost, publish)?;
917 let name = c_string(event);
918 check(unsafe { call(self.plugin, name.as_ptr(), payload) }, || {
920 format!("publish {event}")
921 })
922 }
923
924 pub unsafe fn register_service<T: Sync>(
933 &self,
934 name: &str,
935 version: u32,
936 service: &'static T,
937 ) -> Result<()> {
938 let call = function!(self.table, AnvilHost, register_service)?;
939 let name_c = c_string(name);
940 let result = unsafe {
942 call(
943 self.plugin,
944 name_c.as_ptr(),
945 version,
946 ptr::from_ref(service).cast(),
947 )
948 };
949 check(result, || format!("register_service {name} v{version}"))
950 }
951
952 pub unsafe fn service<T>(&self, name: &CStr, version: u32) -> Option<Table<T>> {
965 let call = field!(self.table, AnvilHost, get_service).flatten()?;
966 unsafe { Table::from_raw(call(self.plugin, name.as_ptr(), version).cast::<T>()) }
970 }
971}
972
973fn bytes_or_null(bytes: &[u8]) -> *const c_void {
974 if bytes.is_empty() {
975 ptr::null()
976 } else {
977 bytes.as_ptr().cast()
978 }
979}