diff options
Diffstat (limited to 'bindgen/codegen/dyngen.rs')
-rw-r--r-- | bindgen/codegen/dyngen.rs | 38 |
1 files changed, 27 insertions, 11 deletions
diff --git a/bindgen/codegen/dyngen.rs b/bindgen/codegen/dyngen.rs index f310f14e..5e734ccd 100644 --- a/bindgen/codegen/dyngen.rs +++ b/bindgen/codegen/dyngen.rs @@ -1,4 +1,5 @@ use crate::codegen; +use crate::ir::context::BindgenContext; use crate::ir::function::ClangAbi; use proc_macro2::Ident; @@ -72,12 +73,22 @@ impl DynamicItems { Self::default() } - pub fn get_tokens(&self, lib_ident: Ident) -> proc_macro2::TokenStream { + pub fn get_tokens( + &self, + lib_ident: Ident, + ctx: &BindgenContext, + ) -> proc_macro2::TokenStream { let struct_members = &self.struct_members; let constructor_inits = &self.constructor_inits; let init_fields = &self.init_fields; let struct_implementation = &self.struct_implementation; + let from_library = if ctx.options().wrap_unsafe_ops { + quote!(unsafe { Self::from_library(library) }) + } else { + quote!(Self::from_library(library)) + }; + quote! { extern crate libloading; @@ -92,9 +103,7 @@ impl DynamicItems { ) -> Result<Self, ::libloading::Error> where P: AsRef<::std::ffi::OsStr> { let library = ::libloading::Library::new(path)?; - unsafe { - Self::from_library(library) - } + #from_library } pub unsafe fn from_library<L>( @@ -126,6 +135,7 @@ impl DynamicItems { ret: proc_macro2::TokenStream, ret_ty: proc_macro2::TokenStream, attributes: Vec<proc_macro2::TokenStream>, + ctx: &BindgenContext, ) { if !is_variadic { assert_eq!(args.len(), args_identifiers.len()); @@ -149,8 +159,10 @@ impl DynamicItems { } else { quote! { self.#ident.as_ref().expect("Expected function, got error.") } }; - let call_body = quote! { - (#fn_)(#( #args_identifiers ),*) + let call_body = if ctx.options().wrap_unsafe_ops { + quote!(unsafe { (#fn_)(#( #args_identifiers ),*) }) + } else { + quote!((#fn_)(#( #args_identifiers ),*) ) }; // We can't implement variadic functions from C easily, so we allow to @@ -159,22 +171,26 @@ impl DynamicItems { self.struct_implementation.push(quote! { #(#attributes)* pub unsafe fn #ident ( &self, #( #args ),* ) -> #ret_ty { - unsafe { - #call_body - } + #call_body } }); } // N.B: Unwrap the signature upon construction if it is required to be resolved. let ident_str = codegen::helpers::ast_ty::cstr_expr(ident.to_string()); + let library_get = if ctx.options().wrap_unsafe_ops { + quote!(unsafe { __library.get(#ident_str) }) + } else { + quote!(__library.get(#ident_str)) + }; + self.constructor_inits.push(if is_required { quote! { - let #ident = unsafe { __library.get(#ident_str) }.map(|sym| *sym)?; + let #ident = #library_get.map(|sym| *sym)?; } } else { quote! { - let #ident = unsafe { __library.get(#ident_str) }.map(|sym| *sym); + let #ident = #library_get.map(|sym| *sym); } }); |