Merge pull request #40 from TheBlueMatt/main
authorMatt Corallo <649246+TheBlueMatt@users.noreply.github.com>
Thu, 19 Aug 2021 18:29:35 +0000 (18:29 +0000)
committerGitHub <noreply@github.com>
Thu, 19 Aug 2021 18:29:35 +0000 (18:29 +0000)
Differentiate inner pointers representing None and Some(ZST)

27 files changed:
c-bindings-gen/src/blocks.rs
c-bindings-gen/src/main.rs
c-bindings-gen/src/types.rs
genbindings.sh
lightning-c-bindings/Cargo.toml
lightning-c-bindings/include/lightning.h
lightning-c-bindings/src/c_types/mod.rs
lightning-c-bindings/src/lightning/chain/chainmonitor.rs
lightning-c-bindings/src/lightning/chain/channelmonitor.rs
lightning-c-bindings/src/lightning/chain/keysinterface.rs
lightning-c-bindings/src/lightning/chain/mod.rs
lightning-c-bindings/src/lightning/chain/transaction.rs
lightning-c-bindings/src/lightning/ln/chan_utils.rs
lightning-c-bindings/src/lightning/ln/channelmanager.rs
lightning-c-bindings/src/lightning/ln/features.rs
lightning-c-bindings/src/lightning/ln/msgs.rs
lightning-c-bindings/src/lightning/ln/peer_handler.rs
lightning-c-bindings/src/lightning/ln/script.rs
lightning-c-bindings/src/lightning/routing/network_graph.rs
lightning-c-bindings/src/lightning/routing/router.rs
lightning-c-bindings/src/lightning/util/config.rs
lightning-c-bindings/src/lightning/util/errors.rs
lightning-c-bindings/src/lightning/util/events.rs
lightning-c-bindings/src/lightning_background_processor.rs
lightning-c-bindings/src/lightning_invoice/mod.rs
lightning-c-bindings/src/lightning_invoice/utils.rs
lightning-c-bindings/src/lightning_persister.rs

index 9c404411a2719d4b979e8b920d1f0ef516e7b3c8..2bbe298189cb54f54d2bfd695ce1be04fe77cf71 100644 (file)
@@ -697,7 +697,7 @@ pub fn write_method_call_params<W: std::io::Write>(w: &mut W, sig: &syn::Signatu
                                write!(w, "ret").unwrap();
                        } else if !to_c && self_segs_iter.is_some() && self_segs_iter.unwrap().next().is_none() {
                                // If we're returning "Self" (and not "Self::X"), just do it manually
-                               write!(w, "{} {{ inner: Box::into_raw(Box::new(ret)), is_owned: true }}", this_type).unwrap();
+                               write!(w, "{} {{ inner: ObjOps::heap_alloc(ret), is_owned: true }}", this_type).unwrap();
                        } else if to_c {
                                let new_var = types.write_from_c_conversion_new_var(w, &format_ident!("ret"), rtype, generics);
                                if new_var {
index 2f94e432e4f351c36e8f975cb531d1d57258f7ba..ce69294928af16714f3e7b645d34cbc2faa9f510 100644 (file)
@@ -563,7 +563,7 @@ fn writeln_opaque<W: std::io::Write>(w: &mut W, ident: &syn::Ident, struct_name:
        writeln!(w, "}}\n").unwrap();
        writeln!(w, "impl Drop for {} {{\n\tfn drop(&mut self) {{", struct_name).unwrap();
        writeln!(w, "\t\tif self.is_owned && !<*mut native{}>::is_null(self.inner) {{", ident).unwrap();
-       writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(self.inner) }};\n\t\t}}\n\t}}\n}}").unwrap();
+       writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(ObjOps::untweak_ptr(self.inner)) }};\n\t\t}}\n\t}}\n}}").unwrap();
        writeln!(w, "/// Frees any resources used by the {}, if is_owned is set and inner is non-NULL.", struct_name).unwrap();
        writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_obj: {}) {{ }}", struct_name, struct_name).unwrap();
        writeln!(w, "#[allow(unused)]").unwrap();
@@ -571,11 +571,17 @@ fn writeln_opaque<W: std::io::Write>(w: &mut W, ident: &syn::Ident, struct_name:
        writeln!(w, "extern \"C\" fn {}_free_void(this_ptr: *mut c_void) {{", struct_name).unwrap();
        writeln!(w, "\tunsafe {{ let _ = Box::from_raw(this_ptr as *mut native{}); }}\n}}", struct_name).unwrap();
        writeln!(w, "#[allow(unused)]").unwrap();
-       writeln!(w, "/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
        writeln!(w, "impl {} {{", struct_name).unwrap();
+       writeln!(w, "\tpub(crate) fn get_native_ref(&self) -> &'static native{} {{", struct_name).unwrap();
+       writeln!(w, "\t\tunsafe {{ &*ObjOps::untweak_ptr(self.inner) }}").unwrap();
+       writeln!(w, "\t}}").unwrap();
+       writeln!(w, "\tpub(crate) fn get_native_mut_ref(&self) -> &'static mut native{} {{", struct_name).unwrap();
+       writeln!(w, "\t\tunsafe {{ &mut *ObjOps::untweak_ptr(self.inner) }}").unwrap();
+       writeln!(w, "\t}}").unwrap();
+       writeln!(w, "\t/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy").unwrap();
        writeln!(w, "\tpub(crate) fn take_inner(mut self) -> *mut native{} {{", struct_name).unwrap();
        writeln!(w, "\t\tassert!(self.is_owned);").unwrap();
-       writeln!(w, "\t\tlet ret = self.inner;").unwrap();
+       writeln!(w, "\t\tlet ret = ObjOps::untweak_ptr(self.inner);").unwrap();
        writeln!(w, "\t\tself.inner = std::ptr::null_mut();").unwrap();
        writeln!(w, "\t\tret").unwrap();
        writeln!(w, "\t}}\n}}").unwrap();
@@ -620,7 +626,7 @@ fn writeln_struct<'a, 'b, W: std::io::Write>(w: &mut W, s: &'a syn::ItemStruct,
                                                writeln_arg_docs(w, &field.attrs, "", types, Some(&gen_types), vec![].drain(..), Some(&ref_type));
                                                write!(w, "#[no_mangle]\npub extern \"C\" fn {}_get_{}(this_ptr: &{}) -> ", struct_name, ident, struct_name).unwrap();
                                                types.write_c_type(w, &ref_type, Some(&gen_types), true);
-                                               write!(w, " {{\n\tlet mut inner_val = &mut unsafe {{ &mut *this_ptr.inner }}.{};\n\t", ident).unwrap();
+                                               write!(w, " {{\n\tlet mut inner_val = &mut this_ptr.get_native_mut_ref().{};\n\t", ident).unwrap();
                                                let local_var = types.write_to_c_conversion_new_var(w, &format_ident!("inner_val"), &ref_type, Some(&gen_types), true);
                                                if local_var { write!(w, "\n\t").unwrap(); }
                                                types.write_to_c_conversion_inline_prefix(w, &ref_type, Some(&gen_types), true);
@@ -636,7 +642,7 @@ fn writeln_struct<'a, 'b, W: std::io::Write>(w: &mut W, s: &'a syn::ItemStruct,
                                                write!(w, ") {{\n\t").unwrap();
                                                let local_var = types.write_from_c_conversion_new_var(w, &format_ident!("val"), &field.ty, Some(&gen_types));
                                                if local_var { write!(w, "\n\t").unwrap(); }
-                                               write!(w, "unsafe {{ &mut *this_ptr.inner }}.{} = ", ident).unwrap();
+                                               write!(w, "unsafe {{ &mut *ObjOps::untweak_ptr(this_ptr.inner) }}.{} = ", ident).unwrap();
                                                types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
                                                write!(w, "val").unwrap();
                                                types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
@@ -662,7 +668,7 @@ fn writeln_struct<'a, 'b, W: std::io::Write>(w: &mut W, s: &'a syn::ItemStruct,
                                        write!(w, "\n\t").unwrap();
                                }
                        }
-                       writeln!(w, "{} {{ inner: Box::into_raw(Box::new(native{} {{", struct_name, s.ident).unwrap();
+                       writeln!(w, "{} {{ inner: ObjOps::heap_alloc(native{} {{", struct_name, s.ident).unwrap();
                        for field in fields.named.iter() {
                                write!(w, "\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
                                types.write_from_c_conversion_prefix(w, &field.ty, Some(&gen_types));
@@ -670,7 +676,7 @@ fn writeln_struct<'a, 'b, W: std::io::Write>(w: &mut W, s: &'a syn::ItemStruct,
                                types.write_from_c_conversion_suffix(w, &field.ty, Some(&gen_types));
                                writeln!(w, ",").unwrap();
                        }
-                       writeln!(w, "\t}})), is_owned: true }}\n}}").unwrap();
+                       writeln!(w, "\t}}), is_owned: true }}\n}}").unwrap();
                }
        }
 }
@@ -764,7 +770,7 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                // type-conversion logic without actually knowing the concrete native type.
                                                writeln!(w, "impl From<native{}> for crate::{} {{", ident, full_trait_path).unwrap();
                                                writeln!(w, "\tfn from(obj: native{}) -> Self {{", ident).unwrap();
-                                               writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: Box::into_raw(Box::new(obj)), is_owned: true }};", ident).unwrap();
+                                               writeln!(w, "\t\tlet mut rust_obj = {} {{ inner: ObjOps::heap_alloc(obj), is_owned: true }};", ident).unwrap();
                                                writeln!(w, "\t\tlet mut ret = {}_as_{}(&rust_obj);", ident, trait_obj.ident).unwrap();
                                                writeln!(w, "\t\t// We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn").unwrap();
                                                writeln!(w, "\t\trust_obj.inner = std::ptr::null_mut();").unwrap();
@@ -775,7 +781,7 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                writeln!(w, "/// This copies the `inner` pointer in this_arg and thus the returned {} must be freed before this_arg is", trait_obj.ident).unwrap();
                                                write!(w, "#[no_mangle]\npub extern \"C\" fn {}_as_{}(this_arg: &{}) -> crate::{} {{\n", ident, trait_obj.ident, ident, full_trait_path).unwrap();
                                                writeln!(w, "\tcrate::{} {{", full_trait_path).unwrap();
-                                               writeln!(w, "\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
+                                               writeln!(w, "\t\tthis_arg: unsafe {{ ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }},").unwrap();
                                                writeln!(w, "\t\tfree: None,").unwrap();
 
                                                macro_rules! write_meth {
@@ -826,7 +832,7 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                        (s, t) => {
                                                                if let Some(supertrait_obj) = types.crate_types.traits.get(s) {
                                                                        writeln!(w, "\t\t{}: crate::{} {{", t, s).unwrap();
-                                                                       writeln!(w, "\t\t\tthis_arg: unsafe {{ (*this_arg).inner as *mut c_void }},").unwrap();
+                                                                       writeln!(w, "\t\t\tthis_arg: unsafe {{ ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }},").unwrap();
                                                                        writeln!(w, "\t\t\tfree: None,").unwrap();
                                                                        for item in supertrait_obj.items.iter() {
                                                                                match item {
@@ -941,7 +947,7 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                        } else if path_matches_nongeneric(&trait_path.1, &["Default"]) {
                                                writeln!(w, "/// Creates a \"default\" {}. See struct and individual field documentaiton for details on which values are used.", ident).unwrap();
                                                write!(w, "#[must_use]\n#[no_mangle]\npub extern \"C\" fn {}_default() -> {} {{\n", ident, ident).unwrap();
-                                               write!(w, "\t{} {{ inner: Box::into_raw(Box::new(Default::default())), is_owned: true }}\n", ident).unwrap();
+                                               write!(w, "\t{} {{ inner: ObjOps::heap_alloc(Default::default()), is_owned: true }}\n", ident).unwrap();
                                                write!(w, "}}\n").unwrap();
                                        } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "PartialEq"]) {
                                        } else if path_matches_nongeneric(&trait_path.1, &["core", "cmp", "Eq"]) {
@@ -996,7 +1002,7 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
                                                writeln!(w, "\t\tSelf {{").unwrap();
                                                writeln!(w, "\t\t\tinner: if <*mut native{}>::is_null(self.inner) {{ std::ptr::null_mut() }} else {{", ident).unwrap();
-                                               writeln!(w, "\t\t\t\tBox::into_raw(Box::new(unsafe {{ &*self.inner }}.clone())) }},").unwrap();
+                                               writeln!(w, "\t\t\t\tObjOps::heap_alloc(unsafe {{ &*ObjOps::untweak_ptr(self.inner) }}.clone()) }},").unwrap();
                                                writeln!(w, "\t\t\tis_owned: true,").unwrap();
                                                writeln!(w, "\t\t}}\n\t}}\n}}").unwrap();
                                                writeln!(w, "#[allow(unused)]").unwrap();
@@ -1093,9 +1099,9 @@ fn writeln_impl<W: std::io::Write>(w: &mut W, i: &syn::ItemImpl, types: &mut Typ
                                                                                                if takes_owned_self {
                                                                                                        write!(w, "(*unsafe {{ Box::from_raw(this_arg.take_inner()) }}).{}(", m.sig.ident).unwrap();
                                                                                                } else if takes_mut_self {
-                                                                                                       write!(w, "unsafe {{ &mut (*(this_arg.inner as *mut native{})) }}.{}(", ident, m.sig.ident).unwrap();
+                                                                                                       write!(w, "unsafe {{ &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut native{})) }}.{}(", ident, m.sig.ident).unwrap();
                                                                                                } else {
-                                                                                                       write!(w, "unsafe {{ &*this_arg.inner }}.{}(", m.sig.ident).unwrap();
+                                                                                                       write!(w, "unsafe {{ &*ObjOps::untweak_ptr(this_arg.inner) }}.{}(", m.sig.ident).unwrap();
                                                                                                }
                                                                                        },
                                                                                        _ => unimplemented!(),
index d19897d3bd653784fd27a22ba9d038289bffd19f..d17148fe25d1378d2ecec2d9c1f2a4f10394f8e5 100644 (file)
@@ -1339,9 +1339,9 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                                let is_inner_ref = if let Some(syn::Type::Reference(_)) = single_contained { true } else { false };
                                                if is_ref {
                                                        return Some(("if ", vec![
-                                                               (".is_none() { std::ptr::null() } else { ".to_owned(),
+                                                               (".is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner(".to_owned(),
                                                                        format!("({}{}.unwrap())", var_access, if is_inner_ref { "" } else { ".as_ref()" }))
-                                                               ], " }", ContainerPrefixLocation::OutsideConv));
+                                                               ], ") }", ContainerPrefixLocation::OutsideConv));
                                                } else {
                                                        return Some(("if ", vec![
                                                                (".is_none() { std::ptr::null_mut() } else { ".to_owned(), format!("({}.unwrap())", var_access))
@@ -1866,14 +1866,14 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                                DeclType::MirroredEnum => write!(w, "crate::{}::native_into(", decl_path).unwrap(),
                                                DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
                                                        write!(w, "crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
-                                               DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
-                                                       write!(w, "crate::{} {{ inner: unsafe {{ ( (&(*", decl_path).unwrap(),
-                                               DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
-                                                       write!(w, "&crate::{} {{ inner: unsafe {{ (", decl_path).unwrap(),
+                                               DeclType::EnumIgnored|DeclType::StructImported if is_ref => {
+                                                       if !ptr_for_ref { write!(w, "&").unwrap(); }
+                                                       write!(w, "crate::{} {{ inner: unsafe {{ ObjOps::nonnull_ptr_to_inner((", decl_path).unwrap()
+                                               },
                                                DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
                                                        write!(w, "crate::{} {{ inner: ", decl_path).unwrap(),
                                                DeclType::EnumIgnored|DeclType::StructImported if !is_ref =>
-                                                       write!(w, "crate::{} {{ inner: Box::into_raw(Box::new(", decl_path).unwrap(),
+                                                       write!(w, "crate::{} {{ inner: ObjOps::heap_alloc(", decl_path).unwrap(),
                                                DeclType::Trait(_) if is_ref => write!(w, "").unwrap(),
                                                DeclType::Trait(_) if !is_ref => {},
                                                _ => panic!("{:?}", decl_path),
@@ -1890,13 +1890,11 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                        DeclType::MirroredEnum => write!(w, ")").unwrap(),
                                        DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref && from_ptr =>
                                                write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
-                                       DeclType::EnumIgnored|DeclType::StructImported if is_ref && ptr_for_ref =>
-                                               write!(w, ") as *const _) as *mut _) }}, is_owned: false }}").unwrap(),
                                        DeclType::EnumIgnored|DeclType::StructImported if is_ref =>
-                                               write!(w, " as *const _) as *mut _ }}, is_owned: false }}").unwrap(),
+                                               write!(w, " as *const _) as *mut _) }}, is_owned: false }}").unwrap(),
                                        DeclType::EnumIgnored|DeclType::StructImported if !is_ref && from_ptr =>
                                                write!(w, ", is_owned: true }}").unwrap(),
-                                       DeclType::EnumIgnored|DeclType::StructImported if !is_ref => write!(w, ")), is_owned: true }}").unwrap(),
+                                       DeclType::EnumIgnored|DeclType::StructImported if !is_ref => write!(w, "), is_owned: true }}").unwrap(),
                                        DeclType::Trait(_) if is_ref => {},
                                        DeclType::Trait(_) => {
                                                // This is used when we're converting a concrete Rust type into a C trait
@@ -1912,13 +1910,11 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                self.write_to_c_conversion_inline_suffix_inner(w, t, generics, false, ptr_for_ref, false);
        }
 
-       fn write_from_c_conversion_prefix_inner<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, ptr_for_ref: bool) {
+       fn write_from_c_conversion_prefix_inner<W: std::io::Write>(&self, w: &mut W, t: &syn::Type, generics: Option<&GenericTypes>, is_ref: bool, _ptr_for_ref: bool) {
                self.write_conversion_inline_intern(w, t, generics, is_ref, false, false, "() /*", true, |_, _| "&local_".to_owned(),
                                |a, b, _c| self.from_c_conversion_prefix_from_path(a, b),
-                               |w, decl_type, _full_path, is_ref, is_mut| match decl_type {
-                                       DeclType::StructImported if is_ref && ptr_for_ref => write!(w, "unsafe {{ &*(*").unwrap(),
-                                       DeclType::StructImported if is_mut && is_ref => write!(w, "unsafe {{ &mut *").unwrap(),
-                                       DeclType::StructImported if is_ref => write!(w, "unsafe {{ &*").unwrap(),
+                               |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
+                                       DeclType::StructImported if is_ref => write!(w, "").unwrap(),
                                        DeclType::StructImported if !is_ref => write!(w, "*unsafe {{ Box::from_raw(").unwrap(),
                                        DeclType::MirroredEnum if is_ref => write!(w, "&").unwrap(),
                                        DeclType::MirroredEnum => {},
@@ -1938,9 +1934,10 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                        (true, Some(_)) => unreachable!(),
                                },
                                |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
-                               |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
-                                       DeclType::StructImported if is_ref && ptr_for_ref => write!(w, ").inner }}").unwrap(),
-                                       DeclType::StructImported if is_ref => write!(w, ".inner }}").unwrap(),
+                               |w, decl_type, _full_path, is_ref, is_mut| match decl_type {
+                                       DeclType::StructImported if is_ref && ptr_for_ref => write!(w, "XXX unimplemented").unwrap(),
+                                       DeclType::StructImported if is_mut && is_ref => write!(w, ".get_native_mut_ref()").unwrap(),
+                                       DeclType::StructImported if is_ref => write!(w, ".get_native_ref()").unwrap(),
                                        DeclType::StructImported if !is_ref => write!(w, ".take_inner()) }}").unwrap(),
                                        DeclType::MirroredEnum if is_ref => write!(w, ".to_native()").unwrap(),
                                        DeclType::MirroredEnum => write!(w, ".into_native()").unwrap(),
@@ -1961,7 +1958,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                        } else { None }
                                },
                                |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
-                                       DeclType::StructImported if !is_ref => write!(w, "unsafe {{ &*").unwrap(),
+                                       DeclType::StructImported if !is_ref => write!(w, "").unwrap(),
                                        _ => unimplemented!(),
                                });
        }
@@ -1975,7 +1972,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                },
                                |a, b, _c| self.from_c_conversion_suffix_from_path(a, b),
                                |w, decl_type, _full_path, is_ref, _is_mut| match decl_type {
-                                       DeclType::StructImported if !is_ref => write!(w, ".inner }}").unwrap(),
+                                       DeclType::StructImported if !is_ref => write!(w, ".get_native_ref()").unwrap(),
                                        _ => unimplemented!(),
                                });
        }
@@ -2064,14 +2061,14 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                                if prefix_location == ContainerPrefixLocation::PerConv {
                                                        var_prefix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
                                                } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
-                                                       write!(w, "Box::into_raw(Box::new(").unwrap();
+                                                       write!(w, "ObjOps::heap_alloc(").unwrap();
                                                }
 
                                                write!(w, "{}{}", if contains_slice { "local_" } else { "" }, if new_var { new_var_name } else { var_access }).unwrap();
                                                if prefix_location == ContainerPrefixLocation::PerConv {
                                                        var_suffix(w, conv_ty, generics, is_ref && ty_has_inner, ptr_for_ref, false);
                                                } else if !is_ref && !needs_ref_map && to_c && only_contained_has_inner {
-                                                       write!(w, "))").unwrap();
+                                                       write!(w, ")").unwrap();
                                                }
                                                write!(w, " }}").unwrap();
                                        }
index c1bfc8dde3cc6b993c7ba1de73f0cd0af7bf8074..3aa2f005390c19ed71a6a5acdca9d4d553c466b6 100755 (executable)
@@ -183,7 +183,7 @@ echo -e '}' >> lightning-c-bindings/src/version.rs
 # Now cd to lightning-c-bindings, build the generated bindings, and call cbindgen to build a C header file
 cd lightning-c-bindings
 
-cargo build
+RUSTFLAGS="$RUSTFLAGS --cfg=test_mod_pointers" cargo build
 if [ "$CFLAGS_aarch64_apple_darwin" != "" ]; then
        RUSTFLAGS="$BASE_RUSTFLAGS -C target-cpu=apple-a14" cargo build --target aarch64-apple-darwin
 fi
@@ -403,7 +403,7 @@ if [ "$HOST_PLATFORM" = "host: x86_64-unknown-linux-gnu" -o "$HOST_PLATFORM" = "
                if [ "$CFLAGS_aarch64_apple_darwin" != "" ]; then
                        RUSTFLAGS="$BASE_RUSTFLAGS -C target-cpu=apple-a14" RUSTC_BOOTSTRAP=1 cargo rustc --target aarch64-apple-darwin -v -- -Zsanitizer=address -Cforce-frame-pointers=yes || ( mv Cargo.toml.bk Cargo.toml; exit 1)
                fi
-               RUSTC_BOOTSTRAP=1 cargo rustc -v -- -Zsanitizer=address -Cforce-frame-pointers=yes || ( mv Cargo.toml.bk Cargo.toml; exit 1)
+               RUSTFLAGS="$RUSTFLAGS --cfg=test_mod_pointers" RUSTC_BOOTSTRAP=1 cargo rustc -v -- -Zsanitizer=address -Cforce-frame-pointers=yes || ( mv Cargo.toml.bk Cargo.toml; exit 1)
                mv Cargo.toml.bk Cargo.toml
 
                # First the C demo app...
index 6d579bfb51aa0daf79d1af41f41536ed54b23310..19edb0aef009f3180bd2c8ca39b14494dd1e6dc3 100644 (file)
@@ -18,10 +18,10 @@ crate-type = ["staticlib"
 bitcoin = "0.27"
 secp256k1 = { version = "0.20.3", features = ["global-context-less-secure"] }
 # Note that the following line is matched by genbindings to update the path
-lightning = { git = "https://github.com/rust-bitcoin/rust-lightning", rev = "v0.0.100", features = ["allow_wallclock_use"] }
-lightning-persister = { git = "https://github.com/rust-bitcoin/rust-lightning", rev = "v0.0.100" }
-lightning-invoice = { git = "https://github.com/rust-bitcoin/rust-lightning", rev = "v0.0.100" }
-lightning-background-processor = { git = "https://github.com/rust-bitcoin/rust-lightning", rev = "v0.0.100" }
+lightning = { git = "https://github.com/rust-bitcoin/rust-lightning", rev = "479ff9018c1a1d49fa8e9036b81bcdcff210a7e5", features = ["allow_wallclock_use"] }
+lightning-persister = { git = "https://github.com/rust-bitcoin/rust-lightning", rev = "479ff9018c1a1d49fa8e9036b81bcdcff210a7e5" }
+lightning-invoice = { git = "https://github.com/rust-bitcoin/rust-lightning", rev = "479ff9018c1a1d49fa8e9036b81bcdcff210a7e5" }
+lightning-background-processor = { git = "https://github.com/rust-bitcoin/rust-lightning", rev = "479ff9018c1a1d49fa8e9036b81bcdcff210a7e5" }
 
 # Always force panic=abort, further options are set in the genbindings.sh build script
 [profile.dev]
index ea3e972ee8a4e67ee37a042b8e47e0f35ba11a8f..9529ff757c0d6da158cb10c1619fa62a6130bcbb 100644 (file)
@@ -18379,7 +18379,10 @@ MUST_USE_RES struct LDKShutdownScript ShutdownScript_new_p2wpkh(const uint8_t (*
 MUST_USE_RES struct LDKShutdownScript ShutdownScript_new_p2wsh(const uint8_t (*script_hash)[32]);
 
 /**
- * Generates a P2WSH script pubkey from the given segwit version and program.
+ * Generates a witness script pubkey from the given segwit version and program.
+ *
+ * Note for version-zero witness scripts you must use [`ShutdownScript::new_p2wpkh`] or
+ * [`ShutdownScript::new_p2wsh`] instead.
  *
  * # Errors
  *
index 2648a9b39092dbdf96576e4dc998cae10eaf8282..09c8a5147d4c096fea4c1313af2497a659072269 100644 (file)
@@ -527,3 +527,51 @@ impl<T> TakePointer<*mut T> for *mut T {
                ret
        }
 }
+
+
+pub(crate) mod ObjOps {
+       #[inline]
+       #[must_use = "returns new dangling pointer"]
+       pub(crate) fn heap_alloc<T>(obj: T) -> *mut T {
+               let ptr = Box::into_raw(Box::new(obj));
+               nonnull_ptr_to_inner(ptr)
+       }
+       #[inline]
+       pub(crate) fn nonnull_ptr_to_inner<T>(ptr: *const T) -> *mut T {
+               if core::mem::size_of::<T>() == 0 {
+                       // We map `None::<T>` as `T { inner: null, .. }` which works great for all
+                       // non-Zero-Sized-Types `T`.
+                       // For ZSTs, we need to differentiate between null implying `None` and null implying
+                       // `Some` with no allocation.
+                       // Thus, for ZSTs, we add one (usually) page here, which should always be aligned.
+                       // Note that this relies on undefined behavior! A pointer to NULL may be valid, but a
+                       // pointer to NULL + 4096 is almost certainly not. That said, Rust's existing use of
+                       // `(*mut T)1` for the pointer we're adding to is also not defined, so we should be
+                       // fine.
+                       // Note that we add 4095 here as at least the Java client assumes that the low bit on
+                       // any heap pointer is 0, which is generally provided by malloc, but which is not true
+                       // for ZSTs "allocated" by `Box::new`.
+                       debug_assert_eq!(ptr as usize, 1);
+                       unsafe { (ptr as *mut T).cast::<u8>().add(4096 - 1).cast::<T>() }
+               } else {
+                       // In order to get better test coverage, also increment non-ZST pointers with
+                       // --cfg=test_mod_pointers, which is set in genbindings.sh for debug builds.
+                       #[cfg(test_mod_pointers)]
+                       unsafe { (ptr as *mut T).cast::<u8>().add(4096).cast::<T>() }
+                       #[cfg(not(test_mod_pointers))]
+                       unsafe { ptr as *mut T }
+               }
+       }
+       #[inline]
+       /// Invert nonnull_ptr_to_inner
+       pub(crate) fn untweak_ptr<T>(ptr: *mut T) -> *mut T {
+               if core::mem::size_of::<T>() == 0 {
+                       unsafe { ptr.cast::<u8>().sub(4096 - 1).cast::<T>() }
+               } else {
+                       #[cfg(test_mod_pointers)]
+                       unsafe { ptr.cast::<u8>().sub(4096).cast::<T>() }
+                       #[cfg(not(test_mod_pointers))]
+                       ptr
+               }
+       }
+}
index 311c2f397cd432025d14db3dfd2c0e2dea71f470..147889c27ac4d32ba929ba5c6a9a988dec648335 100644 (file)
@@ -58,7 +58,7 @@ pub struct ChainMonitor {
 impl Drop for ChainMonitor {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeChainMonitor>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -71,11 +71,17 @@ extern "C" fn ChainMonitor_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChainMonitor); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChainMonitor {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeChainMonitor {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChainMonitor {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeChainMonitor {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -94,12 +100,12 @@ impl ChainMonitor {
 pub extern "C" fn ChainMonitor_new(chain_source: *mut crate::lightning::chain::Filter, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut logger: crate::lightning::util::logger::Logger, mut feeest: crate::lightning::chain::chaininterface::FeeEstimator, mut persister: crate::lightning::chain::channelmonitor::Persist) -> ChainMonitor {
        let mut local_chain_source = if chain_source == std::ptr::null_mut() { None } else { Some( { unsafe { *Box::from_raw(chain_source) } }) };
        let mut ret = lightning::chain::chainmonitor::ChainMonitor::new(local_chain_source, broadcaster, logger, feeest, persister);
-       ChainMonitor { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       ChainMonitor { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 impl From<nativeChainMonitor> for crate::lightning::chain::Listen {
        fn from(obj: nativeChainMonitor) -> Self {
-               let mut rust_obj = ChainMonitor { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut rust_obj = ChainMonitor { inner: ObjOps::heap_alloc(obj), is_owned: true };
                let mut ret = ChainMonitor_as_Listen(&rust_obj);
                // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
                rust_obj.inner = std::ptr::null_mut();
@@ -112,7 +118,7 @@ impl From<nativeChainMonitor> for crate::lightning::chain::Listen {
 #[no_mangle]
 pub extern "C" fn ChainMonitor_as_Listen(this_arg: &ChainMonitor) -> crate::lightning::chain::Listen {
        crate::lightning::chain::Listen {
-               this_arg: unsafe { (*this_arg).inner as *mut c_void },
+               this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
                free: None,
                block_connected: ChainMonitor_Listen_block_connected,
                block_disconnected: ChainMonitor_Listen_block_disconnected,
@@ -128,7 +134,7 @@ extern "C" fn ChainMonitor_Listen_block_disconnected(this_arg: *const c_void, he
 
 impl From<nativeChainMonitor> for crate::lightning::chain::Confirm {
        fn from(obj: nativeChainMonitor) -> Self {
-               let mut rust_obj = ChainMonitor { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut rust_obj = ChainMonitor { inner: ObjOps::heap_alloc(obj), is_owned: true };
                let mut ret = ChainMonitor_as_Confirm(&rust_obj);
                // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
                rust_obj.inner = std::ptr::null_mut();
@@ -141,7 +147,7 @@ impl From<nativeChainMonitor> for crate::lightning::chain::Confirm {
 #[no_mangle]
 pub extern "C" fn ChainMonitor_as_Confirm(this_arg: &ChainMonitor) -> crate::lightning::chain::Confirm {
        crate::lightning::chain::Confirm {
-               this_arg: unsafe { (*this_arg).inner as *mut c_void },
+               this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
                free: None,
                transactions_confirmed: ChainMonitor_Confirm_transactions_confirmed,
                transaction_unconfirmed: ChainMonitor_Confirm_transaction_unconfirmed,
@@ -169,7 +175,7 @@ extern "C" fn ChainMonitor_Confirm_get_relevant_txids(this_arg: *const c_void) -
 
 impl From<nativeChainMonitor> for crate::lightning::chain::Watch {
        fn from(obj: nativeChainMonitor) -> Self {
-               let mut rust_obj = ChainMonitor { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut rust_obj = ChainMonitor { inner: ObjOps::heap_alloc(obj), is_owned: true };
                let mut ret = ChainMonitor_as_Watch(&rust_obj);
                // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
                rust_obj.inner = std::ptr::null_mut();
@@ -182,7 +188,7 @@ impl From<nativeChainMonitor> for crate::lightning::chain::Watch {
 #[no_mangle]
 pub extern "C" fn ChainMonitor_as_Watch(this_arg: &ChainMonitor) -> crate::lightning::chain::Watch {
        crate::lightning::chain::Watch {
-               this_arg: unsafe { (*this_arg).inner as *mut c_void },
+               this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
                free: None,
                watch_channel: ChainMonitor_Watch_watch_channel,
                update_channel: ChainMonitor_Watch_update_channel,
@@ -211,7 +217,7 @@ extern "C" fn ChainMonitor_Watch_release_pending_monitor_events(this_arg: *const
 
 impl From<nativeChainMonitor> for crate::lightning::util::events::EventsProvider {
        fn from(obj: nativeChainMonitor) -> Self {
-               let mut rust_obj = ChainMonitor { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut rust_obj = ChainMonitor { inner: ObjOps::heap_alloc(obj), is_owned: true };
                let mut ret = ChainMonitor_as_EventsProvider(&rust_obj);
                // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
                rust_obj.inner = std::ptr::null_mut();
@@ -224,7 +230,7 @@ impl From<nativeChainMonitor> for crate::lightning::util::events::EventsProvider
 #[no_mangle]
 pub extern "C" fn ChainMonitor_as_EventsProvider(this_arg: &ChainMonitor) -> crate::lightning::util::events::EventsProvider {
        crate::lightning::util::events::EventsProvider {
-               this_arg: unsafe { (*this_arg).inner as *mut c_void },
+               this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
                free: None,
                process_pending_events: ChainMonitor_EventsProvider_process_pending_events,
        }
index 11612160ec4b3c78d551a2ab7565a2e002fbf9dc..ff5043f6b855c8f58dd07adda28b935da98807df 100644 (file)
@@ -48,7 +48,7 @@ pub struct ChannelMonitorUpdate {
 impl Drop for ChannelMonitorUpdate {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeChannelMonitorUpdate>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -61,11 +61,17 @@ extern "C" fn ChannelMonitorUpdate_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelMonitorUpdate); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelMonitorUpdate {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeChannelMonitorUpdate {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelMonitorUpdate {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeChannelMonitorUpdate {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -83,7 +89,7 @@ impl ChannelMonitorUpdate {
 /// its docs for more details.
 #[no_mangle]
 pub extern "C" fn ChannelMonitorUpdate_get_update_id(this_ptr: &ChannelMonitorUpdate) -> u64 {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.update_id;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().update_id;
        *inner_val
 }
 /// The sequence number of this update. Updates *must* be replayed in-order according to this
@@ -99,13 +105,13 @@ pub extern "C" fn ChannelMonitorUpdate_get_update_id(this_ptr: &ChannelMonitorUp
 /// its docs for more details.
 #[no_mangle]
 pub extern "C" fn ChannelMonitorUpdate_set_update_id(this_ptr: &mut ChannelMonitorUpdate, mut val: u64) {
-       unsafe { &mut *this_ptr.inner }.update_id = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.update_id = val;
 }
 impl Clone for ChannelMonitorUpdate {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeChannelMonitorUpdate>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -133,7 +139,7 @@ pub static CLOSED_CHANNEL_UPDATE_ID: u64 = lightning::chain::channelmonitor::CLO
 #[no_mangle]
 /// Serialize the ChannelMonitorUpdate object into a byte array which can be read by ChannelMonitorUpdate_read
 pub extern "C" fn ChannelMonitorUpdate_write(obj: &ChannelMonitorUpdate) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }
 #[no_mangle]
 pub(crate) extern "C" fn ChannelMonitorUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
@@ -143,7 +149,7 @@ pub(crate) extern "C" fn ChannelMonitorUpdate_write_void(obj: *const c_void) ->
 /// Read a ChannelMonitorUpdate from a byte array, created by ChannelMonitorUpdate_write
 pub extern "C" fn ChannelMonitorUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelMonitorUpdateDecodeErrorZ {
        let res = crate::c_types::deserialize_obj(ser);
-       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_res
 }
 /// An error enum representing a failure to persist a channel monitor update.
@@ -279,7 +285,7 @@ pub struct MonitorUpdateError {
 impl Drop for MonitorUpdateError {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeMonitorUpdateError>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -292,11 +298,17 @@ extern "C" fn MonitorUpdateError_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMonitorUpdateError); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl MonitorUpdateError {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeMonitorUpdateError {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMonitorUpdateError {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeMonitorUpdateError {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -305,7 +317,7 @@ impl Clone for MonitorUpdateError {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeMonitorUpdateError>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -370,13 +382,13 @@ impl MonitorEvent {
                        nativeMonitorEvent::HTLCEvent (ref a, ) => {
                                let mut a_nonref = (*a).clone();
                                MonitorEvent::HTLCEvent (
-                                       crate::lightning::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true },
+                                       crate::lightning::chain::channelmonitor::HTLCUpdate { inner: ObjOps::heap_alloc(a_nonref), is_owned: true },
                                )
                        },
                        nativeMonitorEvent::CommitmentTxBroadcasted (ref a, ) => {
                                let mut a_nonref = (*a).clone();
                                MonitorEvent::CommitmentTxBroadcasted (
-                                       crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true },
+                                       crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(a_nonref), is_owned: true },
                                )
                        },
                }
@@ -386,12 +398,12 @@ impl MonitorEvent {
                match native {
                        nativeMonitorEvent::HTLCEvent (mut a, ) => {
                                MonitorEvent::HTLCEvent (
-                                       crate::lightning::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(a)), is_owned: true },
+                                       crate::lightning::chain::channelmonitor::HTLCUpdate { inner: ObjOps::heap_alloc(a), is_owned: true },
                                )
                        },
                        nativeMonitorEvent::CommitmentTxBroadcasted (mut a, ) => {
                                MonitorEvent::CommitmentTxBroadcasted (
-                                       crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(a)), is_owned: true },
+                                       crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(a), is_owned: true },
                                )
                        },
                }
@@ -440,7 +452,7 @@ pub struct HTLCUpdate {
 impl Drop for HTLCUpdate {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeHTLCUpdate>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -453,11 +465,17 @@ extern "C" fn HTLCUpdate_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeHTLCUpdate); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl HTLCUpdate {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeHTLCUpdate {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeHTLCUpdate {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeHTLCUpdate {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -466,7 +484,7 @@ impl Clone for HTLCUpdate {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeHTLCUpdate>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -484,7 +502,7 @@ pub extern "C" fn HTLCUpdate_clone(orig: &HTLCUpdate) -> HTLCUpdate {
 #[no_mangle]
 /// Serialize the HTLCUpdate object into a byte array which can be read by HTLCUpdate_read
 pub extern "C" fn HTLCUpdate_write(obj: &HTLCUpdate) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }
 #[no_mangle]
 pub(crate) extern "C" fn HTLCUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
@@ -494,7 +512,7 @@ pub(crate) extern "C" fn HTLCUpdate_write_void(obj: *const c_void) -> crate::c_t
 /// Read a HTLCUpdate from a byte array, created by HTLCUpdate_write
 pub extern "C" fn HTLCUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_HTLCUpdateDecodeErrorZ {
        let res = crate::c_types::deserialize_obj(ser);
-       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::channelmonitor::HTLCUpdate { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_res
 }
 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding inbound
@@ -540,7 +558,7 @@ pub struct ChannelMonitor {
 impl Drop for ChannelMonitor {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeChannelMonitor>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -553,11 +571,17 @@ extern "C" fn ChannelMonitor_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelMonitor); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelMonitor {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeChannelMonitor {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelMonitor {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeChannelMonitor {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -565,7 +589,7 @@ impl ChannelMonitor {
 #[no_mangle]
 /// Serialize the ChannelMonitor object into a byte array which can be read by ChannelMonitor_read
 pub extern "C" fn ChannelMonitor_write(obj: &ChannelMonitor) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }
 #[no_mangle]
 pub(crate) extern "C" fn ChannelMonitor_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
@@ -578,8 +602,8 @@ pub(crate) extern "C" fn ChannelMonitor_write_void(obj: *const c_void) -> crate:
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_update_monitor(this_arg: &ChannelMonitor, updates: &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate, broadcaster: &crate::lightning::chain::chaininterface::BroadcasterInterface, fee_estimator: &crate::lightning::chain::chaininterface::FeeEstimator, logger: &crate::lightning::util::logger::Logger) -> crate::c_types::derived::CResult_NoneMonitorUpdateErrorZ {
-       let mut ret = unsafe { &*this_arg.inner }.update_monitor(unsafe { &*updates.inner }, broadcaster, fee_estimator, logger);
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::chain::channelmonitor::MonitorUpdateError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.update_monitor(updates.get_native_ref(), broadcaster, fee_estimator, logger);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::chain::channelmonitor::MonitorUpdateError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_ret
 }
 
@@ -588,7 +612,7 @@ pub extern "C" fn ChannelMonitor_update_monitor(this_arg: &ChannelMonitor, updat
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_get_latest_update_id(this_arg: &ChannelMonitor) -> u64 {
-       let mut ret = unsafe { &*this_arg.inner }.get_latest_update_id();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_latest_update_id();
        ret
 }
 
@@ -596,8 +620,8 @@ pub extern "C" fn ChannelMonitor_get_latest_update_id(this_arg: &ChannelMonitor)
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_get_funding_txo(this_arg: &ChannelMonitor) -> crate::c_types::derived::C2Tuple_OutPointScriptZ {
-       let mut ret = unsafe { &*this_arg.inner }.get_funding_txo();
-       let (mut orig_ret_0, mut orig_ret_1) = ret; let mut local_ret = (crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(orig_ret_0)), is_owned: true }, orig_ret_1.into_bytes().into()).into();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_funding_txo();
+       let (mut orig_ret_0, mut orig_ret_1) = ret; let mut local_ret = (crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(orig_ret_0), is_owned: true }, orig_ret_1.into_bytes().into()).into();
        local_ret
 }
 
@@ -606,7 +630,7 @@ pub extern "C" fn ChannelMonitor_get_funding_txo(this_arg: &ChannelMonitor) -> c
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_get_outputs_to_watch(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_C2Tuple_TxidCVec_C2Tuple_u32ScriptZZZZ {
-       let mut ret = unsafe { &*this_arg.inner }.get_outputs_to_watch();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_outputs_to_watch();
        let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1) = item; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { let (mut orig_orig_ret_0_1_0_0, mut orig_orig_ret_0_1_0_1) = item; let mut local_orig_ret_0_1_0 = (orig_orig_ret_0_1_0_0, orig_orig_ret_0_1_0_1.into_bytes().into()).into(); local_orig_ret_0_1_0 }); }; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.into_inner() }, local_orig_ret_0_1.into()).into(); local_ret_0 }); };
        local_ret.into()
 }
@@ -616,7 +640,7 @@ pub extern "C" fn ChannelMonitor_get_outputs_to_watch(this_arg: &ChannelMonitor)
 /// have been registered.
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_load_outputs_to_watch(this_arg: &ChannelMonitor, filter: &crate::lightning::chain::Filter) {
-       unsafe { &*this_arg.inner }.load_outputs_to_watch(filter)
+       unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.load_outputs_to_watch(filter)
 }
 
 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
@@ -624,7 +648,7 @@ pub extern "C" fn ChannelMonitor_load_outputs_to_watch(this_arg: &ChannelMonitor
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_get_and_clear_pending_monitor_events(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_MonitorEventZ {
-       let mut ret = unsafe { &*this_arg.inner }.get_and_clear_pending_monitor_events();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_and_clear_pending_monitor_events();
        let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::chain::channelmonitor::MonitorEvent::native_into(item) }); };
        local_ret.into()
 }
@@ -638,7 +662,7 @@ pub extern "C" fn ChannelMonitor_get_and_clear_pending_monitor_events(this_arg:
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_get_and_clear_pending_events(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_EventZ {
-       let mut ret = unsafe { &*this_arg.inner }.get_and_clear_pending_events();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_and_clear_pending_events();
        let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::util::events::Event::native_into(item) }); };
        local_ret.into()
 }
@@ -655,7 +679,7 @@ pub extern "C" fn ChannelMonitor_get_and_clear_pending_events(this_arg: &Channel
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_get_latest_holder_commitment_txn(this_arg: &ChannelMonitor, logger: &crate::lightning::util::logger::Logger) -> crate::c_types::derived::CVec_TransactionZ {
-       let mut ret = unsafe { &*this_arg.inner }.get_latest_holder_commitment_txn(logger);
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_latest_holder_commitment_txn(logger);
        let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::Transaction::from_bitcoin(&item) }); };
        local_ret.into()
 }
@@ -675,7 +699,7 @@ pub extern "C" fn ChannelMonitor_get_latest_holder_commitment_txn(this_arg: &Cha
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_block_connected(this_arg: &ChannelMonitor, header: *const [u8; 80], mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, mut height: u32, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut logger: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CVec_TransactionOutputsZ {
        let mut local_txdata = Vec::new(); for mut item in txdata.into_rust().drain(..) { local_txdata.push( { let (mut orig_txdata_0_0, mut orig_txdata_0_1) = item.to_rust(); let mut local_txdata_0 = (orig_txdata_0_0, orig_txdata_0_1.into_bitcoin()); local_txdata_0 }); };
-       let mut ret = unsafe { &*this_arg.inner }.block_connected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::<Vec<_>>()[..], height, broadcaster, fee_estimator, logger);
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.block_connected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::<Vec<_>>()[..], height, broadcaster, fee_estimator, logger);
        let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1) = item; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { let (mut orig_orig_ret_0_1_0_0, mut orig_orig_ret_0_1_0_1) = item; let mut local_orig_ret_0_1_0 = (orig_orig_ret_0_1_0_0, crate::c_types::TxOut::from_rust(orig_orig_ret_0_1_0_1)).into(); local_orig_ret_0_1_0 }); }; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.into_inner() }, local_orig_ret_0_1.into()).into(); local_ret_0 }); };
        local_ret.into()
 }
@@ -684,7 +708,7 @@ pub extern "C" fn ChannelMonitor_block_connected(this_arg: &ChannelMonitor, head
 /// appropriately.
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_block_disconnected(this_arg: &ChannelMonitor, header: *const [u8; 80], mut height: u32, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut logger: crate::lightning::util::logger::Logger) {
-       unsafe { &*this_arg.inner }.block_disconnected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height, broadcaster, fee_estimator, logger)
+       unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.block_disconnected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height, broadcaster, fee_estimator, logger)
 }
 
 /// Processes transactions confirmed in a block with the given header and height, returning new
@@ -698,7 +722,7 @@ pub extern "C" fn ChannelMonitor_block_disconnected(this_arg: &ChannelMonitor, h
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_transactions_confirmed(this_arg: &ChannelMonitor, header: *const [u8; 80], mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, mut height: u32, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut logger: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CVec_TransactionOutputsZ {
        let mut local_txdata = Vec::new(); for mut item in txdata.into_rust().drain(..) { local_txdata.push( { let (mut orig_txdata_0_0, mut orig_txdata_0_1) = item.to_rust(); let mut local_txdata_0 = (orig_txdata_0_0, orig_txdata_0_1.into_bitcoin()); local_txdata_0 }); };
-       let mut ret = unsafe { &*this_arg.inner }.transactions_confirmed(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::<Vec<_>>()[..], height, broadcaster, fee_estimator, logger);
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.transactions_confirmed(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::<Vec<_>>()[..], height, broadcaster, fee_estimator, logger);
        let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1) = item; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { let (mut orig_orig_ret_0_1_0_0, mut orig_orig_ret_0_1_0_1) = item; let mut local_orig_ret_0_1_0 = (orig_orig_ret_0_1_0_0, crate::c_types::TxOut::from_rust(orig_orig_ret_0_1_0_1)).into(); local_orig_ret_0_1_0 }); }; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.into_inner() }, local_orig_ret_0_1.into()).into(); local_ret_0 }); };
        local_ret.into()
 }
@@ -711,7 +735,7 @@ pub extern "C" fn ChannelMonitor_transactions_confirmed(this_arg: &ChannelMonito
 /// [`block_disconnected`]: Self::block_disconnected
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_transaction_unconfirmed(this_arg: &ChannelMonitor, txid: *const [u8; 32], mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut logger: crate::lightning::util::logger::Logger) {
-       unsafe { &*this_arg.inner }.transaction_unconfirmed(&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*txid }[..]).unwrap(), broadcaster, fee_estimator, logger)
+       unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.transaction_unconfirmed(&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*txid }[..]).unwrap(), broadcaster, fee_estimator, logger)
 }
 
 /// Updates the monitor with the current best chain tip, returning new outputs to watch. See
@@ -724,7 +748,7 @@ pub extern "C" fn ChannelMonitor_transaction_unconfirmed(this_arg: &ChannelMonit
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_best_block_updated(this_arg: &ChannelMonitor, header: *const [u8; 80], mut height: u32, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut logger: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CVec_TransactionOutputsZ {
-       let mut ret = unsafe { &*this_arg.inner }.best_block_updated(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height, broadcaster, fee_estimator, logger);
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.best_block_updated(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height, broadcaster, fee_estimator, logger);
        let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1) = item; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { let (mut orig_orig_ret_0_1_0_0, mut orig_orig_ret_0_1_0_1) = item; let mut local_orig_ret_0_1_0 = (orig_orig_ret_0_1_0_0, crate::c_types::TxOut::from_rust(orig_orig_ret_0_1_0_1)).into(); local_orig_ret_0_1_0 }); }; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.into_inner() }, local_orig_ret_0_1.into()).into(); local_ret_0 }); };
        local_ret.into()
 }
@@ -733,7 +757,7 @@ pub extern "C" fn ChannelMonitor_best_block_updated(this_arg: &ChannelMonitor, h
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_get_relevant_txids(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_TxidZ {
-       let mut ret = unsafe { &*this_arg.inner }.get_relevant_txids();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_relevant_txids();
        let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::ThirtyTwoBytes { data: item.into_inner() } }); };
        local_ret.into()
 }
@@ -743,8 +767,8 @@ pub extern "C" fn ChannelMonitor_get_relevant_txids(this_arg: &ChannelMonitor) -
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelMonitor_current_best_block(this_arg: &ChannelMonitor) -> crate::lightning::chain::BestBlock {
-       let mut ret = unsafe { &*this_arg.inner }.current_best_block();
-       crate::lightning::chain::BestBlock { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.current_best_block();
+       crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 /// `Persist` defines behavior for persisting channel monitors: this could mean
@@ -816,12 +840,12 @@ pub(crate) extern "C" fn Persist_clone_fields(orig: &Persist) -> Persist {
 use lightning::chain::channelmonitor::Persist as rustPersist;
 impl rustPersist<crate::lightning::chain::keysinterface::Sign> for Persist {
        fn persist_new_channel(&self, mut id: lightning::chain::transaction::OutPoint, mut data: &lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::chain::keysinterface::Sign>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
-               let mut ret = (self.persist_new_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(id)), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { (data as *const _) as *mut _ }, is_owned: false });
+               let mut ret = (self.persist_new_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(id), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { ObjOps::nonnull_ptr_to_inner((data as *const _) as *mut _) }, is_owned: false });
                let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
                local_ret
        }
        fn update_persisted_channel(&self, mut id: lightning::chain::transaction::OutPoint, mut update: &lightning::chain::channelmonitor::ChannelMonitorUpdate, mut data: &lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::chain::keysinterface::Sign>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
-               let mut ret = (self.update_persisted_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(id)), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: unsafe { (update as *const _) as *mut _ }, is_owned: false }, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { (data as *const _) as *mut _ }, is_owned: false });
+               let mut ret = (self.update_persisted_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(id), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: unsafe { ObjOps::nonnull_ptr_to_inner((update as *const _) as *mut _) }, is_owned: false }, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { ObjOps::nonnull_ptr_to_inner((data as *const _) as *mut _) }, is_owned: false });
                let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
                local_ret
        }
@@ -850,6 +874,6 @@ impl Drop for Persist {
 pub extern "C" fn C2Tuple_BlockHashChannelMonitorZ_read(ser: crate::c_types::u8slice, arg: &crate::lightning::chain::keysinterface::KeysInterface) -> crate::c_types::derived::CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ {
        let arg_conv = arg;
        let res: Result<(bitcoin::hash_types::BlockHash, lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::chain::keysinterface::Sign>), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
-       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_res_0_0, mut orig_res_0_1) = o; let mut local_res_0 = (crate::c_types::ThirtyTwoBytes { data: orig_res_0_0.into_inner() }, crate::lightning::chain::channelmonitor::ChannelMonitor { inner: Box::into_raw(Box::new(orig_res_0_1)), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_res_0_0, mut orig_res_0_1) = o; let mut local_res_0 = (crate::c_types::ThirtyTwoBytes { data: orig_res_0_0.into_inner() }, crate::lightning::chain::channelmonitor::ChannelMonitor { inner: ObjOps::heap_alloc(orig_res_0_1), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_res
 }
index 1f542b429eb08be3c6baeb02886e9bdbb85efbe4..ed6df195e792582944154dcfbb85d97753a05aa7 100644 (file)
@@ -39,7 +39,7 @@ pub struct DelayedPaymentOutputDescriptor {
 impl Drop for DelayedPaymentOutputDescriptor {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeDelayedPaymentOutputDescriptor>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -52,11 +52,17 @@ extern "C" fn DelayedPaymentOutputDescriptor_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeDelayedPaymentOutputDescriptor); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl DelayedPaymentOutputDescriptor {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeDelayedPaymentOutputDescriptor {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeDelayedPaymentOutputDescriptor {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeDelayedPaymentOutputDescriptor {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -64,62 +70,62 @@ impl DelayedPaymentOutputDescriptor {
 /// The outpoint which is spendable
 #[no_mangle]
 pub extern "C" fn DelayedPaymentOutputDescriptor_get_outpoint(this_ptr: &DelayedPaymentOutputDescriptor) -> crate::lightning::chain::transaction::OutPoint {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.outpoint;
-       crate::lightning::chain::transaction::OutPoint { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false }
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().outpoint;
+       crate::lightning::chain::transaction::OutPoint { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false }
 }
 /// The outpoint which is spendable
 #[no_mangle]
 pub extern "C" fn DelayedPaymentOutputDescriptor_set_outpoint(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::lightning::chain::transaction::OutPoint) {
-       unsafe { &mut *this_ptr.inner }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// Per commitment point to derive delayed_payment_key by key holder
 #[no_mangle]
 pub extern "C" fn DelayedPaymentOutputDescriptor_get_per_commitment_point(this_ptr: &DelayedPaymentOutputDescriptor) -> crate::c_types::PublicKey {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.per_commitment_point;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().per_commitment_point;
        crate::c_types::PublicKey::from_rust(&inner_val)
 }
 /// Per commitment point to derive delayed_payment_key by key holder
 #[no_mangle]
 pub extern "C" fn DelayedPaymentOutputDescriptor_set_per_commitment_point(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::c_types::PublicKey) {
-       unsafe { &mut *this_ptr.inner }.per_commitment_point = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.per_commitment_point = val.into_rust();
 }
 /// The nSequence value which must be set in the spending input to satisfy the OP_CSV in
 /// the witness_script.
 #[no_mangle]
 pub extern "C" fn DelayedPaymentOutputDescriptor_get_to_self_delay(this_ptr: &DelayedPaymentOutputDescriptor) -> u16 {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.to_self_delay;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().to_self_delay;
        *inner_val
 }
 /// The nSequence value which must be set in the spending input to satisfy the OP_CSV in
 /// the witness_script.
 #[no_mangle]
 pub extern "C" fn DelayedPaymentOutputDescriptor_set_to_self_delay(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: u16) {
-       unsafe { &mut *this_ptr.inner }.to_self_delay = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.to_self_delay = val;
 }
 /// The output which is referenced by the given outpoint
 #[no_mangle]
 pub extern "C" fn DelayedPaymentOutputDescriptor_set_output(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::c_types::TxOut) {
-       unsafe { &mut *this_ptr.inner }.output = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.output = val.into_rust();
 }
 /// The revocation point specific to the commitment transaction which was broadcast. Used to
 /// derive the witnessScript for this output.
 #[no_mangle]
 pub extern "C" fn DelayedPaymentOutputDescriptor_get_revocation_pubkey(this_ptr: &DelayedPaymentOutputDescriptor) -> crate::c_types::PublicKey {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.revocation_pubkey;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().revocation_pubkey;
        crate::c_types::PublicKey::from_rust(&inner_val)
 }
 /// The revocation point specific to the commitment transaction which was broadcast. Used to
 /// derive the witnessScript for this output.
 #[no_mangle]
 pub extern "C" fn DelayedPaymentOutputDescriptor_set_revocation_pubkey(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::c_types::PublicKey) {
-       unsafe { &mut *this_ptr.inner }.revocation_pubkey = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.revocation_pubkey = val.into_rust();
 }
 /// Arbitrary identification information returned by a call to
 /// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
 /// the channel to spend the output.
 #[no_mangle]
 pub extern "C" fn DelayedPaymentOutputDescriptor_get_channel_keys_id(this_ptr: &DelayedPaymentOutputDescriptor) -> *const [u8; 32] {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_keys_id;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_keys_id;
        inner_val
 }
 /// Arbitrary identification information returned by a call to
@@ -127,24 +133,24 @@ pub extern "C" fn DelayedPaymentOutputDescriptor_get_channel_keys_id(this_ptr: &
 /// the channel to spend the output.
 #[no_mangle]
 pub extern "C" fn DelayedPaymentOutputDescriptor_set_channel_keys_id(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::c_types::ThirtyTwoBytes) {
-       unsafe { &mut *this_ptr.inner }.channel_keys_id = val.data;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_keys_id = val.data;
 }
 /// The value of the channel which this output originated from, possibly indirectly.
 #[no_mangle]
 pub extern "C" fn DelayedPaymentOutputDescriptor_get_channel_value_satoshis(this_ptr: &DelayedPaymentOutputDescriptor) -> u64 {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_value_satoshis;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_value_satoshis;
        *inner_val
 }
 /// The value of the channel which this output originated from, possibly indirectly.
 #[no_mangle]
 pub extern "C" fn DelayedPaymentOutputDescriptor_set_channel_value_satoshis(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: u64) {
-       unsafe { &mut *this_ptr.inner }.channel_value_satoshis = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_value_satoshis = val;
 }
 /// Constructs a new DelayedPaymentOutputDescriptor given each field
 #[must_use]
 #[no_mangle]
 pub extern "C" fn DelayedPaymentOutputDescriptor_new(mut outpoint_arg: crate::lightning::chain::transaction::OutPoint, mut per_commitment_point_arg: crate::c_types::PublicKey, mut to_self_delay_arg: u16, mut output_arg: crate::c_types::TxOut, mut revocation_pubkey_arg: crate::c_types::PublicKey, mut channel_keys_id_arg: crate::c_types::ThirtyTwoBytes, mut channel_value_satoshis_arg: u64) -> DelayedPaymentOutputDescriptor {
-       DelayedPaymentOutputDescriptor { inner: Box::into_raw(Box::new(nativeDelayedPaymentOutputDescriptor {
+       DelayedPaymentOutputDescriptor { inner: ObjOps::heap_alloc(nativeDelayedPaymentOutputDescriptor {
                outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) },
                per_commitment_point: per_commitment_point_arg.into_rust(),
                to_self_delay: to_self_delay_arg,
@@ -152,13 +158,13 @@ pub extern "C" fn DelayedPaymentOutputDescriptor_new(mut outpoint_arg: crate::li
                revocation_pubkey: revocation_pubkey_arg.into_rust(),
                channel_keys_id: channel_keys_id_arg.data,
                channel_value_satoshis: channel_value_satoshis_arg,
-       })), is_owned: true }
+       }), is_owned: true }
 }
 impl Clone for DelayedPaymentOutputDescriptor {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeDelayedPaymentOutputDescriptor>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -176,7 +182,7 @@ pub extern "C" fn DelayedPaymentOutputDescriptor_clone(orig: &DelayedPaymentOutp
 #[no_mangle]
 /// Serialize the DelayedPaymentOutputDescriptor object into a byte array which can be read by DelayedPaymentOutputDescriptor_read
 pub extern "C" fn DelayedPaymentOutputDescriptor_write(obj: &DelayedPaymentOutputDescriptor) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }
 #[no_mangle]
 pub(crate) extern "C" fn DelayedPaymentOutputDescriptor_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
@@ -186,7 +192,7 @@ pub(crate) extern "C" fn DelayedPaymentOutputDescriptor_write_void(obj: *const c
 /// Read a DelayedPaymentOutputDescriptor from a byte array, created by DelayedPaymentOutputDescriptor_write
 pub extern "C" fn DelayedPaymentOutputDescriptor_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_DelayedPaymentOutputDescriptorDecodeErrorZ {
        let res = crate::c_types::deserialize_obj(ser);
-       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::DelayedPaymentOutputDescriptor { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::DelayedPaymentOutputDescriptor { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_res
 }
 
@@ -213,7 +219,7 @@ pub struct StaticPaymentOutputDescriptor {
 impl Drop for StaticPaymentOutputDescriptor {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeStaticPaymentOutputDescriptor>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -226,11 +232,17 @@ extern "C" fn StaticPaymentOutputDescriptor_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeStaticPaymentOutputDescriptor); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl StaticPaymentOutputDescriptor {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeStaticPaymentOutputDescriptor {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeStaticPaymentOutputDescriptor {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeStaticPaymentOutputDescriptor {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -238,25 +250,25 @@ impl StaticPaymentOutputDescriptor {
 /// The outpoint which is spendable
 #[no_mangle]
 pub extern "C" fn StaticPaymentOutputDescriptor_get_outpoint(this_ptr: &StaticPaymentOutputDescriptor) -> crate::lightning::chain::transaction::OutPoint {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.outpoint;
-       crate::lightning::chain::transaction::OutPoint { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false }
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().outpoint;
+       crate::lightning::chain::transaction::OutPoint { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false }
 }
 /// The outpoint which is spendable
 #[no_mangle]
 pub extern "C" fn StaticPaymentOutputDescriptor_set_outpoint(this_ptr: &mut StaticPaymentOutputDescriptor, mut val: crate::lightning::chain::transaction::OutPoint) {
-       unsafe { &mut *this_ptr.inner }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// The output which is referenced by the given outpoint
 #[no_mangle]
 pub extern "C" fn StaticPaymentOutputDescriptor_set_output(this_ptr: &mut StaticPaymentOutputDescriptor, mut val: crate::c_types::TxOut) {
-       unsafe { &mut *this_ptr.inner }.output = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.output = val.into_rust();
 }
 /// Arbitrary identification information returned by a call to
 /// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in
 /// the channel to spend the output.
 #[no_mangle]
 pub extern "C" fn StaticPaymentOutputDescriptor_get_channel_keys_id(this_ptr: &StaticPaymentOutputDescriptor) -> *const [u8; 32] {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_keys_id;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_keys_id;
        inner_val
 }
 /// Arbitrary identification information returned by a call to
@@ -264,35 +276,35 @@ pub extern "C" fn StaticPaymentOutputDescriptor_get_channel_keys_id(this_ptr: &S
 /// the channel to spend the output.
 #[no_mangle]
 pub extern "C" fn StaticPaymentOutputDescriptor_set_channel_keys_id(this_ptr: &mut StaticPaymentOutputDescriptor, mut val: crate::c_types::ThirtyTwoBytes) {
-       unsafe { &mut *this_ptr.inner }.channel_keys_id = val.data;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_keys_id = val.data;
 }
 /// The value of the channel which this transactions spends.
 #[no_mangle]
 pub extern "C" fn StaticPaymentOutputDescriptor_get_channel_value_satoshis(this_ptr: &StaticPaymentOutputDescriptor) -> u64 {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_value_satoshis;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_value_satoshis;
        *inner_val
 }
 /// The value of the channel which this transactions spends.
 #[no_mangle]
 pub extern "C" fn StaticPaymentOutputDescriptor_set_channel_value_satoshis(this_ptr: &mut StaticPaymentOutputDescriptor, mut val: u64) {
-       unsafe { &mut *this_ptr.inner }.channel_value_satoshis = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_value_satoshis = val;
 }
 /// Constructs a new StaticPaymentOutputDescriptor given each field
 #[must_use]
 #[no_mangle]
 pub extern "C" fn StaticPaymentOutputDescriptor_new(mut outpoint_arg: crate::lightning::chain::transaction::OutPoint, mut output_arg: crate::c_types::TxOut, mut channel_keys_id_arg: crate::c_types::ThirtyTwoBytes, mut channel_value_satoshis_arg: u64) -> StaticPaymentOutputDescriptor {
-       StaticPaymentOutputDescriptor { inner: Box::into_raw(Box::new(nativeStaticPaymentOutputDescriptor {
+       StaticPaymentOutputDescriptor { inner: ObjOps::heap_alloc(nativeStaticPaymentOutputDescriptor {
                outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) },
                output: output_arg.into_rust(),
                channel_keys_id: channel_keys_id_arg.data,
                channel_value_satoshis: channel_value_satoshis_arg,
-       })), is_owned: true }
+       }), is_owned: true }
 }
 impl Clone for StaticPaymentOutputDescriptor {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeStaticPaymentOutputDescriptor>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -310,7 +322,7 @@ pub extern "C" fn StaticPaymentOutputDescriptor_clone(orig: &StaticPaymentOutput
 #[no_mangle]
 /// Serialize the StaticPaymentOutputDescriptor object into a byte array which can be read by StaticPaymentOutputDescriptor_read
 pub extern "C" fn StaticPaymentOutputDescriptor_write(obj: &StaticPaymentOutputDescriptor) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }
 #[no_mangle]
 pub(crate) extern "C" fn StaticPaymentOutputDescriptor_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
@@ -320,7 +332,7 @@ pub(crate) extern "C" fn StaticPaymentOutputDescriptor_write_void(obj: *const c_
 /// Read a StaticPaymentOutputDescriptor from a byte array, created by StaticPaymentOutputDescriptor_write
 pub extern "C" fn StaticPaymentOutputDescriptor_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_StaticPaymentOutputDescriptorDecodeErrorZ {
        let res = crate::c_types::deserialize_obj(ser);
-       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::StaticPaymentOutputDescriptor { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::StaticPaymentOutputDescriptor { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_res
 }
 /// When on-chain outputs are created by rust-lightning (which our counterparty is not able to
@@ -436,20 +448,20 @@ impl SpendableOutputDescriptor {
                                let mut outpoint_nonref = (*outpoint).clone();
                                let mut output_nonref = (*output).clone();
                                SpendableOutputDescriptor::StaticOutput {
-                                       outpoint: crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(outpoint_nonref)), is_owned: true },
+                                       outpoint: crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(outpoint_nonref), is_owned: true },
                                        output: crate::c_types::TxOut::from_rust(output_nonref),
                                }
                        },
                        nativeSpendableOutputDescriptor::DelayedPaymentOutput (ref a, ) => {
                                let mut a_nonref = (*a).clone();
                                SpendableOutputDescriptor::DelayedPaymentOutput (
-                                       crate::lightning::chain::keysinterface::DelayedPaymentOutputDescriptor { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true },
+                                       crate::lightning::chain::keysinterface::DelayedPaymentOutputDescriptor { inner: ObjOps::heap_alloc(a_nonref), is_owned: true },
                                )
                        },
                        nativeSpendableOutputDescriptor::StaticPaymentOutput (ref a, ) => {
                                let mut a_nonref = (*a).clone();
                                SpendableOutputDescriptor::StaticPaymentOutput (
-                                       crate::lightning::chain::keysinterface::StaticPaymentOutputDescriptor { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true },
+                                       crate::lightning::chain::keysinterface::StaticPaymentOutputDescriptor { inner: ObjOps::heap_alloc(a_nonref), is_owned: true },
                                )
                        },
                }
@@ -459,18 +471,18 @@ impl SpendableOutputDescriptor {
                match native {
                        nativeSpendableOutputDescriptor::StaticOutput {mut outpoint, mut output, } => {
                                SpendableOutputDescriptor::StaticOutput {
-                                       outpoint: crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(outpoint)), is_owned: true },
+                                       outpoint: crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(outpoint), is_owned: true },
                                        output: crate::c_types::TxOut::from_rust(output),
                                }
                        },
                        nativeSpendableOutputDescriptor::DelayedPaymentOutput (mut a, ) => {
                                SpendableOutputDescriptor::DelayedPaymentOutput (
-                                       crate::lightning::chain::keysinterface::DelayedPaymentOutputDescriptor { inner: Box::into_raw(Box::new(a)), is_owned: true },
+                                       crate::lightning::chain::keysinterface::DelayedPaymentOutputDescriptor { inner: ObjOps::heap_alloc(a), is_owned: true },
                                )
                        },
                        nativeSpendableOutputDescriptor::StaticPaymentOutput (mut a, ) => {
                                SpendableOutputDescriptor::StaticPaymentOutput (
-                                       crate::lightning::chain::keysinterface::StaticPaymentOutputDescriptor { inner: Box::into_raw(Box::new(a)), is_owned: true },
+                                       crate::lightning::chain::keysinterface::StaticPaymentOutputDescriptor { inner: ObjOps::heap_alloc(a), is_owned: true },
                                )
                        },
                }
@@ -511,7 +523,7 @@ pub extern "C" fn SpendableOutputDescriptor_write(obj: &SpendableOutputDescripto
 /// Read a SpendableOutputDescriptor from a byte array, created by SpendableOutputDescriptor_write
 pub extern "C" fn SpendableOutputDescriptor_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_SpendableOutputDescriptorDecodeErrorZ {
        let res = crate::c_types::deserialize_obj(ser);
-       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::SpendableOutputDescriptor::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::SpendableOutputDescriptor::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_res
 }
 /// A trait to sign lightning channel transactions as described in BOLT 3.
@@ -700,19 +712,19 @@ impl rustBaseSign for BaseSign {
                if let Some(f) = self.set_pubkeys {
                        (f)(&self);
                }
-               unsafe { &*self.pubkeys.inner }
+               self.pubkeys.get_native_ref()
        }
        fn channel_keys_id(&self) -> [u8; 32] {
                let mut ret = (self.channel_keys_id)(self.this_arg);
                ret.data
        }
        fn sign_counterparty_commitment(&self, mut commitment_tx: &lightning::ln::chan_utils::CommitmentTransaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> Result<(bitcoin::secp256k1::Signature, Vec<bitcoin::secp256k1::Signature>), ()> {
-               let mut ret = (self.sign_counterparty_commitment)(self.this_arg, &crate::lightning::ln::chan_utils::CommitmentTransaction { inner: unsafe { (commitment_tx as *const _) as *mut _ }, is_owned: false });
+               let mut ret = (self.sign_counterparty_commitment)(self.this_arg, &crate::lightning::ln::chan_utils::CommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((commitment_tx as *const _) as *mut _) }, is_owned: false });
                let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_rust() }); }; let mut local_ret_0 = (orig_ret_0_0.into_rust(), local_orig_ret_0_1); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
        fn sign_holder_commitment_and_htlcs(&self, mut commitment_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> Result<(bitcoin::secp256k1::Signature, Vec<bitcoin::secp256k1::Signature>), ()> {
-               let mut ret = (self.sign_holder_commitment_and_htlcs)(self.this_arg, &crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { (commitment_tx as *const _) as *mut _ }, is_owned: false });
+               let mut ret = (self.sign_holder_commitment_and_htlcs)(self.this_arg, &crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((commitment_tx as *const _) as *mut _) }, is_owned: false });
                let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_rust() }); }; let mut local_ret_0 = (orig_ret_0_0.into_rust(), local_orig_ret_0_1); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
@@ -722,12 +734,12 @@ impl rustBaseSign for BaseSign {
                local_ret
        }
        fn sign_justice_revoked_htlc(&self, mut justice_tx: &bitcoin::blockdata::transaction::Transaction, mut input: usize, mut amount: u64, mut per_commitment_key: &bitcoin::secp256k1::key::SecretKey, mut htlc: &lightning::ln::chan_utils::HTLCOutputInCommitment, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> Result<bitcoin::secp256k1::Signature, ()> {
-               let mut ret = (self.sign_justice_revoked_htlc)(self.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref(), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (htlc as *const _) as *mut _ }, is_owned: false });
+               let mut ret = (self.sign_justice_revoked_htlc)(self.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref(), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { ObjOps::nonnull_ptr_to_inner((htlc as *const _) as *mut _) }, is_owned: false });
                let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
        fn sign_counterparty_htlc_transaction(&self, mut htlc_tx: &bitcoin::blockdata::transaction::Transaction, mut input: usize, mut amount: u64, mut per_commitment_point: &bitcoin::secp256k1::key::PublicKey, mut htlc: &lightning::ln::chan_utils::HTLCOutputInCommitment, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> Result<bitcoin::secp256k1::Signature, ()> {
-               let mut ret = (self.sign_counterparty_htlc_transaction)(self.this_arg, crate::c_types::Transaction::from_bitcoin(htlc_tx), input, amount, crate::c_types::PublicKey::from_rust(&per_commitment_point), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (htlc as *const _) as *mut _ }, is_owned: false });
+               let mut ret = (self.sign_counterparty_htlc_transaction)(self.this_arg, crate::c_types::Transaction::from_bitcoin(htlc_tx), input, amount, crate::c_types::PublicKey::from_rust(&per_commitment_point), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { ObjOps::nonnull_ptr_to_inner((htlc as *const _) as *mut _) }, is_owned: false });
                let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
@@ -737,12 +749,12 @@ impl rustBaseSign for BaseSign {
                local_ret
        }
        fn sign_channel_announcement(&self, mut msg: &lightning::ln::msgs::UnsignedChannelAnnouncement, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> Result<bitcoin::secp256k1::Signature, ()> {
-               let mut ret = (self.sign_channel_announcement)(self.this_arg, &crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false });
+               let mut ret = (self.sign_channel_announcement)(self.this_arg, &crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false });
                let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
        fn ready_channel(&mut self, mut channel_parameters: &lightning::ln::chan_utils::ChannelTransactionParameters) {
-               (self.ready_channel)(self.this_arg, &crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { (channel_parameters as *const _) as *mut _ }, is_owned: false })
+               (self.ready_channel)(self.this_arg, &crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((channel_parameters as *const _) as *mut _) }, is_owned: false })
        }
 }
 
@@ -811,19 +823,19 @@ impl lightning::chain::keysinterface::BaseSign for Sign {
                if let Some(f) = self.BaseSign.set_pubkeys {
                        (f)(&self.BaseSign);
                }
-               unsafe { &*self.BaseSign.pubkeys.inner }
+               self.BaseSign.pubkeys.get_native_ref()
        }
        fn channel_keys_id(&self) -> [u8; 32] {
                let mut ret = (self.BaseSign.channel_keys_id)(self.BaseSign.this_arg);
                ret.data
        }
        fn sign_counterparty_commitment(&self, mut commitment_tx: &lightning::ln::chan_utils::CommitmentTransaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> Result<(bitcoin::secp256k1::Signature, Vec<bitcoin::secp256k1::Signature>), ()> {
-               let mut ret = (self.BaseSign.sign_counterparty_commitment)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::CommitmentTransaction { inner: unsafe { (commitment_tx as *const _) as *mut _ }, is_owned: false });
+               let mut ret = (self.BaseSign.sign_counterparty_commitment)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::CommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((commitment_tx as *const _) as *mut _) }, is_owned: false });
                let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_rust() }); }; let mut local_ret_0 = (orig_ret_0_0.into_rust(), local_orig_ret_0_1); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
        fn sign_holder_commitment_and_htlcs(&self, mut commitment_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> Result<(bitcoin::secp256k1::Signature, Vec<bitcoin::secp256k1::Signature>), ()> {
-               let mut ret = (self.BaseSign.sign_holder_commitment_and_htlcs)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { (commitment_tx as *const _) as *mut _ }, is_owned: false });
+               let mut ret = (self.BaseSign.sign_holder_commitment_and_htlcs)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((commitment_tx as *const _) as *mut _) }, is_owned: false });
                let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_rust() }); }; let mut local_ret_0 = (orig_ret_0_0.into_rust(), local_orig_ret_0_1); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
@@ -833,12 +845,12 @@ impl lightning::chain::keysinterface::BaseSign for Sign {
                local_ret
        }
        fn sign_justice_revoked_htlc(&self, mut justice_tx: &bitcoin::blockdata::transaction::Transaction, mut input: usize, mut amount: u64, mut per_commitment_key: &bitcoin::secp256k1::key::SecretKey, mut htlc: &lightning::ln::chan_utils::HTLCOutputInCommitment, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> Result<bitcoin::secp256k1::Signature, ()> {
-               let mut ret = (self.BaseSign.sign_justice_revoked_htlc)(self.BaseSign.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref(), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (htlc as *const _) as *mut _ }, is_owned: false });
+               let mut ret = (self.BaseSign.sign_justice_revoked_htlc)(self.BaseSign.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref(), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { ObjOps::nonnull_ptr_to_inner((htlc as *const _) as *mut _) }, is_owned: false });
                let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
        fn sign_counterparty_htlc_transaction(&self, mut htlc_tx: &bitcoin::blockdata::transaction::Transaction, mut input: usize, mut amount: u64, mut per_commitment_point: &bitcoin::secp256k1::key::PublicKey, mut htlc: &lightning::ln::chan_utils::HTLCOutputInCommitment, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> Result<bitcoin::secp256k1::Signature, ()> {
-               let mut ret = (self.BaseSign.sign_counterparty_htlc_transaction)(self.BaseSign.this_arg, crate::c_types::Transaction::from_bitcoin(htlc_tx), input, amount, crate::c_types::PublicKey::from_rust(&per_commitment_point), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (htlc as *const _) as *mut _ }, is_owned: false });
+               let mut ret = (self.BaseSign.sign_counterparty_htlc_transaction)(self.BaseSign.this_arg, crate::c_types::Transaction::from_bitcoin(htlc_tx), input, amount, crate::c_types::PublicKey::from_rust(&per_commitment_point), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { ObjOps::nonnull_ptr_to_inner((htlc as *const _) as *mut _) }, is_owned: false });
                let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
@@ -848,12 +860,12 @@ impl lightning::chain::keysinterface::BaseSign for Sign {
                local_ret
        }
        fn sign_channel_announcement(&self, mut msg: &lightning::ln::msgs::UnsignedChannelAnnouncement, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1<bitcoin::secp256k1::All>) -> Result<bitcoin::secp256k1::Signature, ()> {
-               let mut ret = (self.BaseSign.sign_channel_announcement)(self.BaseSign.this_arg, &crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false });
+               let mut ret = (self.BaseSign.sign_channel_announcement)(self.BaseSign.this_arg, &crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false });
                let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
                local_ret
        }
        fn ready_channel(&mut self, mut channel_parameters: &lightning::ln::chan_utils::ChannelTransactionParameters) {
-               (self.BaseSign.ready_channel)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { (channel_parameters as *const _) as *mut _ }, is_owned: false })
+               (self.BaseSign.ready_channel)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((channel_parameters as *const _) as *mut _) }, is_owned: false })
        }
 }
 impl lightning::util::ser::Writeable for Sign {
@@ -1049,7 +1061,7 @@ pub struct InMemorySigner {
 impl Drop for InMemorySigner {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeInMemorySigner>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -1062,11 +1074,17 @@ extern "C" fn InMemorySigner_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInMemorySigner); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl InMemorySigner {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeInMemorySigner {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeInMemorySigner {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeInMemorySigner {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -1074,74 +1092,74 @@ impl InMemorySigner {
 /// Private key of anchor tx
 #[no_mangle]
 pub extern "C" fn InMemorySigner_get_funding_key(this_ptr: &InMemorySigner) -> *const [u8; 32] {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_key;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().funding_key;
        inner_val.as_ref()
 }
 /// Private key of anchor tx
 #[no_mangle]
 pub extern "C" fn InMemorySigner_set_funding_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) {
-       unsafe { &mut *this_ptr.inner }.funding_key = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.funding_key = val.into_rust();
 }
 /// Holder secret key for blinded revocation pubkey
 #[no_mangle]
 pub extern "C" fn InMemorySigner_get_revocation_base_key(this_ptr: &InMemorySigner) -> *const [u8; 32] {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.revocation_base_key;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().revocation_base_key;
        inner_val.as_ref()
 }
 /// Holder secret key for blinded revocation pubkey
 #[no_mangle]
 pub extern "C" fn InMemorySigner_set_revocation_base_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) {
-       unsafe { &mut *this_ptr.inner }.revocation_base_key = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.revocation_base_key = val.into_rust();
 }
 /// Holder secret key used for our balance in counterparty-broadcasted commitment transactions
 #[no_mangle]
 pub extern "C" fn InMemorySigner_get_payment_key(this_ptr: &InMemorySigner) -> *const [u8; 32] {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.payment_key;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().payment_key;
        inner_val.as_ref()
 }
 /// Holder secret key used for our balance in counterparty-broadcasted commitment transactions
 #[no_mangle]
 pub extern "C" fn InMemorySigner_set_payment_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) {
-       unsafe { &mut *this_ptr.inner }.payment_key = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.payment_key = val.into_rust();
 }
 /// Holder secret key used in HTLC tx
 #[no_mangle]
 pub extern "C" fn InMemorySigner_get_delayed_payment_base_key(this_ptr: &InMemorySigner) -> *const [u8; 32] {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.delayed_payment_base_key;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().delayed_payment_base_key;
        inner_val.as_ref()
 }
 /// Holder secret key used in HTLC tx
 #[no_mangle]
 pub extern "C" fn InMemorySigner_set_delayed_payment_base_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) {
-       unsafe { &mut *this_ptr.inner }.delayed_payment_base_key = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.delayed_payment_base_key = val.into_rust();
 }
 /// Holder htlc secret key used in commitment tx htlc outputs
 #[no_mangle]
 pub extern "C" fn InMemorySigner_get_htlc_base_key(this_ptr: &InMemorySigner) -> *const [u8; 32] {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_base_key;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().htlc_base_key;
        inner_val.as_ref()
 }
 /// Holder htlc secret key used in commitment tx htlc outputs
 #[no_mangle]
 pub extern "C" fn InMemorySigner_set_htlc_base_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) {
-       unsafe { &mut *this_ptr.inner }.htlc_base_key = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_base_key = val.into_rust();
 }
 /// Commitment seed
 #[no_mangle]
 pub extern "C" fn InMemorySigner_get_commitment_seed(this_ptr: &InMemorySigner) -> *const [u8; 32] {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.commitment_seed;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().commitment_seed;
        inner_val
 }
 /// Commitment seed
 #[no_mangle]
 pub extern "C" fn InMemorySigner_set_commitment_seed(this_ptr: &mut InMemorySigner, mut val: crate::c_types::ThirtyTwoBytes) {
-       unsafe { &mut *this_ptr.inner }.commitment_seed = val.data;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.commitment_seed = val.data;
 }
 impl Clone for InMemorySigner {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeInMemorySigner>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -1161,7 +1179,7 @@ pub extern "C" fn InMemorySigner_clone(orig: &InMemorySigner) -> InMemorySigner
 #[no_mangle]
 pub extern "C" fn InMemorySigner_new(mut funding_key: crate::c_types::SecretKey, mut revocation_base_key: crate::c_types::SecretKey, mut payment_key: crate::c_types::SecretKey, mut delayed_payment_base_key: crate::c_types::SecretKey, mut htlc_base_key: crate::c_types::SecretKey, mut commitment_seed: crate::c_types::ThirtyTwoBytes, mut channel_value_satoshis: u64, mut channel_keys_id: crate::c_types::ThirtyTwoBytes) -> crate::lightning::chain::keysinterface::InMemorySigner {
        let mut ret = lightning::chain::keysinterface::InMemorySigner::new(secp256k1::SECP256K1, funding_key.into_rust(), revocation_base_key.into_rust(), payment_key.into_rust(), delayed_payment_base_key.into_rust(), htlc_base_key.into_rust(), commitment_seed.data, channel_value_satoshis, channel_keys_id.data);
-       crate::lightning::chain::keysinterface::InMemorySigner { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       crate::lightning::chain::keysinterface::InMemorySigner { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 /// Counterparty pubkeys.
@@ -1169,8 +1187,8 @@ pub extern "C" fn InMemorySigner_new(mut funding_key: crate::c_types::SecretKey,
 #[must_use]
 #[no_mangle]
 pub extern "C" fn InMemorySigner_counterparty_pubkeys(this_arg: &InMemorySigner) -> crate::lightning::ln::chan_utils::ChannelPublicKeys {
-       let mut ret = unsafe { &*this_arg.inner }.counterparty_pubkeys();
-       crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.counterparty_pubkeys();
+       crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false }
 }
 
 /// The contest_delay value specified by our counterparty and applied on holder-broadcastable
@@ -1180,7 +1198,7 @@ pub extern "C" fn InMemorySigner_counterparty_pubkeys(this_arg: &InMemorySigner)
 #[must_use]
 #[no_mangle]
 pub extern "C" fn InMemorySigner_counterparty_selected_contest_delay(this_arg: &InMemorySigner) -> u16 {
-       let mut ret = unsafe { &*this_arg.inner }.counterparty_selected_contest_delay();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.counterparty_selected_contest_delay();
        ret
 }
 
@@ -1191,7 +1209,7 @@ pub extern "C" fn InMemorySigner_counterparty_selected_contest_delay(this_arg: &
 #[must_use]
 #[no_mangle]
 pub extern "C" fn InMemorySigner_holder_selected_contest_delay(this_arg: &InMemorySigner) -> u16 {
-       let mut ret = unsafe { &*this_arg.inner }.holder_selected_contest_delay();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.holder_selected_contest_delay();
        ret
 }
 
@@ -1200,7 +1218,7 @@ pub extern "C" fn InMemorySigner_holder_selected_contest_delay(this_arg: &InMemo
 #[must_use]
 #[no_mangle]
 pub extern "C" fn InMemorySigner_is_outbound(this_arg: &InMemorySigner) -> bool {
-       let mut ret = unsafe { &*this_arg.inner }.is_outbound();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_outbound();
        ret
 }
 
@@ -1209,8 +1227,8 @@ pub extern "C" fn InMemorySigner_is_outbound(this_arg: &InMemorySigner) -> bool
 #[must_use]
 #[no_mangle]
 pub extern "C" fn InMemorySigner_funding_outpoint(this_arg: &InMemorySigner) -> crate::lightning::chain::transaction::OutPoint {
-       let mut ret = unsafe { &*this_arg.inner }.funding_outpoint();
-       crate::lightning::chain::transaction::OutPoint { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.funding_outpoint();
+       crate::lightning::chain::transaction::OutPoint { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false }
 }
 
 /// Obtain a ChannelTransactionParameters for this channel, to be used when verifying or
@@ -1220,8 +1238,8 @@ pub extern "C" fn InMemorySigner_funding_outpoint(this_arg: &InMemorySigner) ->
 #[must_use]
 #[no_mangle]
 pub extern "C" fn InMemorySigner_get_channel_parameters(this_arg: &InMemorySigner) -> crate::lightning::ln::chan_utils::ChannelTransactionParameters {
-       let mut ret = unsafe { &*this_arg.inner }.get_channel_parameters();
-       crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_channel_parameters();
+       crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false }
 }
 
 /// Sign the single input of spend_tx at index `input_idx` which spends the output
@@ -1232,7 +1250,7 @@ pub extern "C" fn InMemorySigner_get_channel_parameters(this_arg: &InMemorySigne
 #[must_use]
 #[no_mangle]
 pub extern "C" fn InMemorySigner_sign_counterparty_payment_input(this_arg: &InMemorySigner, mut spend_tx: crate::c_types::Transaction, mut input_idx: usize, descriptor: &crate::lightning::chain::keysinterface::StaticPaymentOutputDescriptor) -> crate::c_types::derived::CResult_CVec_CVec_u8ZZNoneZ {
-       let mut ret = unsafe { &*this_arg.inner }.sign_counterparty_payment_input(&spend_tx.into_bitcoin(), input_idx, unsafe { &*descriptor.inner }, secp256k1::SECP256K1);
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.sign_counterparty_payment_input(&spend_tx.into_bitcoin(), input_idx, descriptor.get_native_ref(), secp256k1::SECP256K1);
        let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { let mut local_ret_0_0 = Vec::new(); for mut item in item.drain(..) { local_ret_0_0.push( { item }); }; local_ret_0_0.into() }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
        local_ret
 }
@@ -1246,14 +1264,14 @@ pub extern "C" fn InMemorySigner_sign_counterparty_payment_input(this_arg: &InMe
 #[must_use]
 #[no_mangle]
 pub extern "C" fn InMemorySigner_sign_dynamic_p2wsh_input(this_arg: &InMemorySigner, mut spend_tx: crate::c_types::Transaction, mut input_idx: usize, descriptor: &crate::lightning::chain::keysinterface::DelayedPaymentOutputDescriptor) -> crate::c_types::derived::CResult_CVec_CVec_u8ZZNoneZ {
-       let mut ret = unsafe { &*this_arg.inner }.sign_dynamic_p2wsh_input(&spend_tx.into_bitcoin(), input_idx, unsafe { &*descriptor.inner }, secp256k1::SECP256K1);
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.sign_dynamic_p2wsh_input(&spend_tx.into_bitcoin(), input_idx, descriptor.get_native_ref(), secp256k1::SECP256K1);
        let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { let mut local_ret_0_0 = Vec::new(); for mut item in item.drain(..) { local_ret_0_0.push( { item }); }; local_ret_0_0.into() }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
        local_ret
 }
 
 impl From<nativeInMemorySigner> for crate::lightning::chain::keysinterface::BaseSign {
        fn from(obj: nativeInMemorySigner) -> Self {
-               let mut rust_obj = InMemorySigner { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut rust_obj = InMemorySigner { inner: ObjOps::heap_alloc(obj), is_owned: true };
                let mut ret = InMemorySigner_as_BaseSign(&rust_obj);
                // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
                rust_obj.inner = std::ptr::null_mut();
@@ -1266,7 +1284,7 @@ impl From<nativeInMemorySigner> for crate::lightning::chain::keysinterface::Base
 #[no_mangle]
 pub extern "C" fn InMemorySigner_as_BaseSign(this_arg: &InMemorySigner) -> crate::lightning::chain::keysinterface::BaseSign {
        crate::lightning::chain::keysinterface::BaseSign {
-               this_arg: unsafe { (*this_arg).inner as *mut c_void },
+               this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
                free: None,
                get_per_commitment_point: InMemorySigner_BaseSign_get_per_commitment_point,
                release_commitment_secret: InMemorySigner_BaseSign_release_commitment_secret,
@@ -1298,7 +1316,7 @@ extern "C" fn InMemorySigner_BaseSign_release_commitment_secret(this_arg: *const
 #[must_use]
 extern "C" fn InMemorySigner_BaseSign_pubkeys(this_arg: *const c_void) -> crate::lightning::ln::chan_utils::ChannelPublicKeys {
        let mut ret = <nativeInMemorySigner as lightning::chain::keysinterface::BaseSign<>>::pubkeys(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, );
-       crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
+       crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false }
 }
 extern "C" fn InMemorySigner_BaseSign_set_pubkeys(trait_self_arg: &BaseSign) {
        // This is a bit race-y in the general case, but for our specific use-cases today, we're safe
@@ -1314,13 +1332,13 @@ extern "C" fn InMemorySigner_BaseSign_channel_keys_id(this_arg: *const c_void) -
 }
 #[must_use]
 extern "C" fn InMemorySigner_BaseSign_sign_counterparty_commitment(this_arg: *const c_void, commitment_tx: &crate::lightning::ln::chan_utils::CommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
-       let mut ret = <nativeInMemorySigner as lightning::chain::keysinterface::BaseSign<>>::sign_counterparty_commitment(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, unsafe { &*commitment_tx.inner }, secp256k1::SECP256K1);
+       let mut ret = <nativeInMemorySigner as lightning::chain::keysinterface::BaseSign<>>::sign_counterparty_commitment(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, commitment_tx.get_native_ref(), secp256k1::SECP256K1);
        let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::c_types::Signature::from_rust(&item) }); }; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
        local_ret
 }
 #[must_use]
 extern "C" fn InMemorySigner_BaseSign_sign_holder_commitment_and_htlcs(this_arg: *const c_void, commitment_tx: &crate::lightning::ln::chan_utils::HolderCommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ {
-       let mut ret = <nativeInMemorySigner as lightning::chain::keysinterface::BaseSign<>>::sign_holder_commitment_and_htlcs(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, unsafe { &*commitment_tx.inner }, secp256k1::SECP256K1);
+       let mut ret = <nativeInMemorySigner as lightning::chain::keysinterface::BaseSign<>>::sign_holder_commitment_and_htlcs(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, commitment_tx.get_native_ref(), secp256k1::SECP256K1);
        let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::c_types::Signature::from_rust(&item) }); }; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
        local_ret
 }
@@ -1332,13 +1350,13 @@ extern "C" fn InMemorySigner_BaseSign_sign_justice_revoked_output(this_arg: *con
 }
 #[must_use]
 extern "C" fn InMemorySigner_BaseSign_sign_justice_revoked_htlc(this_arg: *const c_void, mut justice_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, per_commitment_key: *const [u8; 32], htlc: &crate::lightning::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ {
-       let mut ret = <nativeInMemorySigner as lightning::chain::keysinterface::BaseSign<>>::sign_justice_revoked_htlc(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &justice_tx.into_bitcoin(), input, amount, &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *per_commitment_key}[..]).unwrap(), unsafe { &*htlc.inner }, secp256k1::SECP256K1);
+       let mut ret = <nativeInMemorySigner as lightning::chain::keysinterface::BaseSign<>>::sign_justice_revoked_htlc(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &justice_tx.into_bitcoin(), input, amount, &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *per_commitment_key}[..]).unwrap(), htlc.get_native_ref(), secp256k1::SECP256K1);
        let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
        local_ret
 }
 #[must_use]
 extern "C" fn InMemorySigner_BaseSign_sign_counterparty_htlc_transaction(this_arg: *const c_void, mut htlc_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, mut per_commitment_point: crate::c_types::PublicKey, htlc: &crate::lightning::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ {
-       let mut ret = <nativeInMemorySigner as lightning::chain::keysinterface::BaseSign<>>::sign_counterparty_htlc_transaction(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &htlc_tx.into_bitcoin(), input, amount, &per_commitment_point.into_rust(), unsafe { &*htlc.inner }, secp256k1::SECP256K1);
+       let mut ret = <nativeInMemorySigner as lightning::chain::keysinterface::BaseSign<>>::sign_counterparty_htlc_transaction(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &htlc_tx.into_bitcoin(), input, amount, &per_commitment_point.into_rust(), htlc.get_native_ref(), secp256k1::SECP256K1);
        let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
        local_ret
 }
@@ -1350,17 +1368,17 @@ extern "C" fn InMemorySigner_BaseSign_sign_closing_transaction(this_arg: *const
 }
 #[must_use]
 extern "C" fn InMemorySigner_BaseSign_sign_channel_announcement(this_arg: *const c_void, msg: &crate::lightning::ln::msgs::UnsignedChannelAnnouncement) -> crate::c_types::derived::CResult_SignatureNoneZ {
-       let mut ret = <nativeInMemorySigner as lightning::chain::keysinterface::BaseSign<>>::sign_channel_announcement(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, unsafe { &*msg.inner }, secp256k1::SECP256K1);
+       let mut ret = <nativeInMemorySigner as lightning::chain::keysinterface::BaseSign<>>::sign_channel_announcement(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, msg.get_native_ref(), secp256k1::SECP256K1);
        let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
        local_ret
 }
 extern "C" fn InMemorySigner_BaseSign_ready_channel(this_arg: *mut c_void, channel_parameters: &crate::lightning::ln::chan_utils::ChannelTransactionParameters) {
-       <nativeInMemorySigner as lightning::chain::keysinterface::BaseSign<>>::ready_channel(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, unsafe { &*channel_parameters.inner })
+       <nativeInMemorySigner as lightning::chain::keysinterface::BaseSign<>>::ready_channel(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, channel_parameters.get_native_ref())
 }
 
 impl From<nativeInMemorySigner> for crate::lightning::chain::keysinterface::Sign {
        fn from(obj: nativeInMemorySigner) -> Self {
-               let mut rust_obj = InMemorySigner { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut rust_obj = InMemorySigner { inner: ObjOps::heap_alloc(obj), is_owned: true };
                let mut ret = InMemorySigner_as_Sign(&rust_obj);
                // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
                rust_obj.inner = std::ptr::null_mut();
@@ -1373,10 +1391,10 @@ impl From<nativeInMemorySigner> for crate::lightning::chain::keysinterface::Sign
 #[no_mangle]
 pub extern "C" fn InMemorySigner_as_Sign(this_arg: &InMemorySigner) -> crate::lightning::chain::keysinterface::Sign {
        crate::lightning::chain::keysinterface::Sign {
-               this_arg: unsafe { (*this_arg).inner as *mut c_void },
+               this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
                free: None,
                BaseSign: crate::lightning::chain::keysinterface::BaseSign {
-                       this_arg: unsafe { (*this_arg).inner as *mut c_void },
+                       this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
                        free: None,
                        get_per_commitment_point: InMemorySigner_BaseSign_get_per_commitment_point,
                        release_commitment_secret: InMemorySigner_BaseSign_release_commitment_secret,
@@ -1408,7 +1426,7 @@ extern "C" fn Sign_InMemorySigner_cloned(new_obj: &mut crate::lightning::chain::
 #[no_mangle]
 /// Serialize the InMemorySigner object into a byte array which can be read by InMemorySigner_read
 pub extern "C" fn InMemorySigner_write(obj: &InMemorySigner) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }
 #[no_mangle]
 pub(crate) extern "C" fn InMemorySigner_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
@@ -1418,7 +1436,7 @@ pub(crate) extern "C" fn InMemorySigner_write_void(obj: *const c_void) -> crate:
 /// Read a InMemorySigner from a byte array, created by InMemorySigner_write
 pub extern "C" fn InMemorySigner_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_InMemorySignerDecodeErrorZ {
        let res = crate::c_types::deserialize_obj(ser);
-       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::InMemorySigner { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::InMemorySigner { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_res
 }
 
@@ -1450,7 +1468,7 @@ pub struct KeysManager {
 impl Drop for KeysManager {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeKeysManager>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -1463,11 +1481,17 @@ extern "C" fn KeysManager_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeKeysManager); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl KeysManager {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeKeysManager {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeKeysManager {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeKeysManager {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -1495,7 +1519,7 @@ impl KeysManager {
 #[no_mangle]
 pub extern "C" fn KeysManager_new(seed: *const [u8; 32], mut starting_time_secs: u64, mut starting_time_nanos: u32) -> KeysManager {
        let mut ret = lightning::chain::keysinterface::KeysManager::new(unsafe { &*seed}, starting_time_secs, starting_time_nanos);
-       KeysManager { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       KeysManager { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 /// Derive an old Sign containing per-channel secrets based on a key derivation parameters.
@@ -1506,8 +1530,8 @@ pub extern "C" fn KeysManager_new(seed: *const [u8; 32], mut starting_time_secs:
 #[must_use]
 #[no_mangle]
 pub extern "C" fn KeysManager_derive_channel_keys(this_arg: &KeysManager, mut channel_value_satoshis: u64, params: *const [u8; 32]) -> crate::lightning::chain::keysinterface::InMemorySigner {
-       let mut ret = unsafe { &*this_arg.inner }.derive_channel_keys(channel_value_satoshis, unsafe { &*params});
-       crate::lightning::chain::keysinterface::InMemorySigner { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.derive_channel_keys(channel_value_satoshis, unsafe { &*params});
+       crate::lightning::chain::keysinterface::InMemorySigner { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 /// Creates a Transaction which spends the given descriptors to the given outputs, plus an
@@ -1526,14 +1550,14 @@ pub extern "C" fn KeysManager_derive_channel_keys(this_arg: &KeysManager, mut ch
 pub extern "C" fn KeysManager_spend_spendable_outputs(this_arg: &KeysManager, mut descriptors: crate::c_types::derived::CVec_SpendableOutputDescriptorZ, mut outputs: crate::c_types::derived::CVec_TxOutZ, mut change_destination_script: crate::c_types::derived::CVec_u8Z, mut feerate_sat_per_1000_weight: u32) -> crate::c_types::derived::CResult_TransactionNoneZ {
        let mut local_descriptors = Vec::new(); for mut item in descriptors.into_rust().drain(..) { local_descriptors.push( { item.into_native() }); };
        let mut local_outputs = Vec::new(); for mut item in outputs.into_rust().drain(..) { local_outputs.push( { item.into_rust() }); };
-       let mut ret = unsafe { &*this_arg.inner }.spend_spendable_outputs(&local_descriptors.iter().collect::<Vec<_>>()[..], local_outputs, ::bitcoin::blockdata::script::Script::from(change_destination_script.into_rust()), feerate_sat_per_1000_weight, secp256k1::SECP256K1);
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.spend_spendable_outputs(&local_descriptors.iter().collect::<Vec<_>>()[..], local_outputs, ::bitcoin::blockdata::script::Script::from(change_destination_script.into_rust()), feerate_sat_per_1000_weight, secp256k1::SECP256K1);
        let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Transaction::from_bitcoin(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
        local_ret
 }
 
 impl From<nativeKeysManager> for crate::lightning::chain::keysinterface::KeysInterface {
        fn from(obj: nativeKeysManager) -> Self {
-               let mut rust_obj = KeysManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut rust_obj = KeysManager { inner: ObjOps::heap_alloc(obj), is_owned: true };
                let mut ret = KeysManager_as_KeysInterface(&rust_obj);
                // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
                rust_obj.inner = std::ptr::null_mut();
@@ -1546,7 +1570,7 @@ impl From<nativeKeysManager> for crate::lightning::chain::keysinterface::KeysInt
 #[no_mangle]
 pub extern "C" fn KeysManager_as_KeysInterface(this_arg: &KeysManager) -> crate::lightning::chain::keysinterface::KeysInterface {
        crate::lightning::chain::keysinterface::KeysInterface {
-               this_arg: unsafe { (*this_arg).inner as *mut c_void },
+               this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
                free: None,
                get_node_secret: KeysManager_KeysInterface_get_node_secret,
                get_destination_script: KeysManager_KeysInterface_get_destination_script,
@@ -1571,7 +1595,7 @@ extern "C" fn KeysManager_KeysInterface_get_destination_script(this_arg: *const
 #[must_use]
 extern "C" fn KeysManager_KeysInterface_get_shutdown_scriptpubkey(this_arg: *const c_void) -> crate::lightning::ln::script::ShutdownScript {
        let mut ret = <nativeKeysManager as lightning::chain::keysinterface::KeysInterface<>>::get_shutdown_scriptpubkey(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, );
-       crate::lightning::ln::script::ShutdownScript { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       crate::lightning::ln::script::ShutdownScript { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 #[must_use]
 extern "C" fn KeysManager_KeysInterface_get_channel_signer(this_arg: *const c_void, mut _inbound: bool, mut channel_value_satoshis: u64) -> crate::lightning::chain::keysinterface::Sign {
@@ -1586,7 +1610,7 @@ extern "C" fn KeysManager_KeysInterface_get_secure_random_bytes(this_arg: *const
 #[must_use]
 extern "C" fn KeysManager_KeysInterface_read_chan_signer(this_arg: *const c_void, mut reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_SignDecodeErrorZ {
        let mut ret = <nativeKeysManager as lightning::chain::keysinterface::KeysInterface<>>::read_chan_signer(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, reader.to_slice());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_ret
 }
 #[must_use]
index 7db473226e706d9756b77edb55daf523e3296b03..9c8b4f5c044f00b82239e33e446fbd01b1ac574e 100644 (file)
@@ -57,7 +57,7 @@ pub struct BestBlock {
 impl Drop for BestBlock {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeBestBlock>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -70,11 +70,17 @@ extern "C" fn BestBlock_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeBestBlock); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl BestBlock {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeBestBlock {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBestBlock {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeBestBlock {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -83,7 +89,7 @@ impl Clone for BestBlock {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeBestBlock>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -104,7 +110,7 @@ pub extern "C" fn BestBlock_clone(orig: &BestBlock) -> BestBlock {
 #[no_mangle]
 pub extern "C" fn BestBlock_from_genesis(mut network: crate::bitcoin::network::Network) -> BestBlock {
        let mut ret = lightning::chain::BestBlock::from_genesis(network.into_bitcoin());
-       BestBlock { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 /// Returns a `BestBlock` as identified by the given block hash and height.
@@ -112,14 +118,14 @@ pub extern "C" fn BestBlock_from_genesis(mut network: crate::bitcoin::network::N
 #[no_mangle]
 pub extern "C" fn BestBlock_new(mut block_hash: crate::c_types::ThirtyTwoBytes, mut height: u32) -> BestBlock {
        let mut ret = lightning::chain::BestBlock::new(::bitcoin::hash_types::BlockHash::from_slice(&block_hash.data[..]).unwrap(), height);
-       BestBlock { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 /// Returns the best block hash.
 #[must_use]
 #[no_mangle]
 pub extern "C" fn BestBlock_block_hash(this_arg: &BestBlock) -> crate::c_types::ThirtyTwoBytes {
-       let mut ret = unsafe { &*this_arg.inner }.block_hash();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.block_hash();
        crate::c_types::ThirtyTwoBytes { data: ret.into_inner() }
 }
 
@@ -127,7 +133,7 @@ pub extern "C" fn BestBlock_block_hash(this_arg: &BestBlock) -> crate::c_types::
 #[must_use]
 #[no_mangle]
 pub extern "C" fn BestBlock_height(this_arg: &BestBlock) -> u32 {
-       let mut ret = unsafe { &*this_arg.inner }.height();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.height();
        ret
 }
 
@@ -510,12 +516,12 @@ pub(crate) extern "C" fn Watch_clone_fields(orig: &Watch) -> Watch {
 use lightning::chain::Watch as rustWatch;
 impl rustWatch<crate::lightning::chain::keysinterface::Sign> for Watch {
        fn watch_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut monitor: lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::chain::keysinterface::Sign>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
-               let mut ret = (self.watch_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(funding_txo)), is_owned: true }, crate::lightning::chain::channelmonitor::ChannelMonitor { inner: Box::into_raw(Box::new(monitor)), is_owned: true });
+               let mut ret = (self.watch_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(funding_txo), is_owned: true }, crate::lightning::chain::channelmonitor::ChannelMonitor { inner: ObjOps::heap_alloc(monitor), is_owned: true });
                let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
                local_ret
        }
        fn update_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut update: lightning::chain::channelmonitor::ChannelMonitorUpdate) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
-               let mut ret = (self.update_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(funding_txo)), is_owned: true }, crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: Box::into_raw(Box::new(update)), is_owned: true });
+               let mut ret = (self.update_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(funding_txo), is_owned: true }, crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: ObjOps::heap_alloc(update), is_owned: true });
                let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
                local_ret
        }
@@ -605,7 +611,7 @@ impl rustFilter for Filter {
                (self.register_tx)(self.this_arg, txid.as_inner(), crate::c_types::u8slice::from_slice(&script_pubkey[..]))
        }
        fn register_output(&self, mut output: lightning::chain::WatchedOutput) -> Option<(usize, bitcoin::blockdata::transaction::Transaction)> {
-               let mut ret = (self.register_output)(self.this_arg, crate::lightning::chain::WatchedOutput { inner: Box::into_raw(Box::new(output)), is_owned: true });
+               let mut ret = (self.register_output)(self.this_arg, crate::lightning::chain::WatchedOutput { inner: ObjOps::heap_alloc(output), is_owned: true });
                let mut local_ret = if ret.is_some() { Some( { let (mut orig_ret_0_0, mut orig_ret_0_1) = ret.take().to_rust(); let mut local_ret_0 = (orig_ret_0_0, orig_ret_0_1.into_bitcoin()); local_ret_0 }) } else { None };
                local_ret
        }
@@ -662,7 +668,7 @@ pub struct WatchedOutput {
 impl Drop for WatchedOutput {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeWatchedOutput>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -675,11 +681,17 @@ extern "C" fn WatchedOutput_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeWatchedOutput); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl WatchedOutput {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeWatchedOutput {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeWatchedOutput {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeWatchedOutput {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -689,7 +701,7 @@ impl WatchedOutput {
 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn WatchedOutput_get_block_hash(this_ptr: &WatchedOutput) -> crate::c_types::ThirtyTwoBytes {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.block_hash;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().block_hash;
        let mut local_inner_val = if inner_val.is_none() { crate::c_types::ThirtyTwoBytes::null() } else {  { crate::c_types::ThirtyTwoBytes { data: (inner_val.unwrap()).into_inner() } } };
        local_inner_val
 }
@@ -699,46 +711,46 @@ pub extern "C" fn WatchedOutput_get_block_hash(this_ptr: &WatchedOutput) -> crat
 #[no_mangle]
 pub extern "C" fn WatchedOutput_set_block_hash(this_ptr: &mut WatchedOutput, mut val: crate::c_types::ThirtyTwoBytes) {
        let mut local_val = if val.data == [0; 32] { None } else { Some( { ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap() }) };
-       unsafe { &mut *this_ptr.inner }.block_hash = local_val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.block_hash = local_val;
 }
 /// Outpoint identifying the transaction output.
 #[no_mangle]
 pub extern "C" fn WatchedOutput_get_outpoint(this_ptr: &WatchedOutput) -> crate::lightning::chain::transaction::OutPoint {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.outpoint;
-       crate::lightning::chain::transaction::OutPoint { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false }
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().outpoint;
+       crate::lightning::chain::transaction::OutPoint { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false }
 }
 /// Outpoint identifying the transaction output.
 #[no_mangle]
 pub extern "C" fn WatchedOutput_set_outpoint(this_ptr: &mut WatchedOutput, mut val: crate::lightning::chain::transaction::OutPoint) {
-       unsafe { &mut *this_ptr.inner }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// Spending condition of the transaction output.
 #[no_mangle]
 pub extern "C" fn WatchedOutput_get_script_pubkey(this_ptr: &WatchedOutput) -> crate::c_types::u8slice {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.script_pubkey;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().script_pubkey;
        crate::c_types::u8slice::from_slice(&inner_val[..])
 }
 /// Spending condition of the transaction output.
 #[no_mangle]
 pub extern "C" fn WatchedOutput_set_script_pubkey(this_ptr: &mut WatchedOutput, mut val: crate::c_types::derived::CVec_u8Z) {
-       unsafe { &mut *this_ptr.inner }.script_pubkey = ::bitcoin::blockdata::script::Script::from(val.into_rust());
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.script_pubkey = ::bitcoin::blockdata::script::Script::from(val.into_rust());
 }
 /// Constructs a new WatchedOutput given each field
 #[must_use]
 #[no_mangle]
 pub extern "C" fn WatchedOutput_new(mut block_hash_arg: crate::c_types::ThirtyTwoBytes, mut outpoint_arg: crate::lightning::chain::transaction::OutPoint, mut script_pubkey_arg: crate::c_types::derived::CVec_u8Z) -> WatchedOutput {
        let mut local_block_hash_arg = if block_hash_arg.data == [0; 32] { None } else { Some( { ::bitcoin::hash_types::BlockHash::from_slice(&block_hash_arg.data[..]).unwrap() }) };
-       WatchedOutput { inner: Box::into_raw(Box::new(nativeWatchedOutput {
+       WatchedOutput { inner: ObjOps::heap_alloc(nativeWatchedOutput {
                block_hash: local_block_hash_arg,
                outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) },
                script_pubkey: ::bitcoin::blockdata::script::Script::from(script_pubkey_arg.into_rust()),
-       })), is_owned: true }
+       }), is_owned: true }
 }
 impl Clone for WatchedOutput {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeWatchedOutput>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -760,6 +772,6 @@ pub extern "C" fn WatchedOutput_hash(o: &WatchedOutput) -> u64 {
        // Note that we'd love to use std::collections::hash_map::DefaultHasher but it's not in core
        #[allow(deprecated)]
        let mut hasher = core::hash::SipHasher::new();
-       std::hash::Hash::hash(unsafe { &*o.inner }, &mut hasher);
+       std::hash::Hash::hash(o.get_native_ref(), &mut hasher);
        std::hash::Hasher::finish(&hasher)
 }
index 45794a14c39029f880df02418fe94b66582930c2..2006596dd5ede442ea152b736b50aac544e541f5 100644 (file)
@@ -39,7 +39,7 @@ pub struct OutPoint {
 impl Drop for OutPoint {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeOutPoint>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -52,11 +52,17 @@ extern "C" fn OutPoint_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeOutPoint); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl OutPoint {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeOutPoint {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOutPoint {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeOutPoint {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -64,39 +70,39 @@ impl OutPoint {
 /// The referenced transaction's txid.
 #[no_mangle]
 pub extern "C" fn OutPoint_get_txid(this_ptr: &OutPoint) -> *const [u8; 32] {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.txid;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().txid;
        inner_val.as_inner()
 }
 /// The referenced transaction's txid.
 #[no_mangle]
 pub extern "C" fn OutPoint_set_txid(this_ptr: &mut OutPoint, mut val: crate::c_types::ThirtyTwoBytes) {
-       unsafe { &mut *this_ptr.inner }.txid = ::bitcoin::hash_types::Txid::from_slice(&val.data[..]).unwrap();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.txid = ::bitcoin::hash_types::Txid::from_slice(&val.data[..]).unwrap();
 }
 /// The index of the referenced output in its transaction's vout.
 #[no_mangle]
 pub extern "C" fn OutPoint_get_index(this_ptr: &OutPoint) -> u16 {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.index;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().index;
        *inner_val
 }
 /// The index of the referenced output in its transaction's vout.
 #[no_mangle]
 pub extern "C" fn OutPoint_set_index(this_ptr: &mut OutPoint, mut val: u16) {
-       unsafe { &mut *this_ptr.inner }.index = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.index = val;
 }
 /// Constructs a new OutPoint given each field
 #[must_use]
 #[no_mangle]
 pub extern "C" fn OutPoint_new(mut txid_arg: crate::c_types::ThirtyTwoBytes, mut index_arg: u16) -> OutPoint {
-       OutPoint { inner: Box::into_raw(Box::new(nativeOutPoint {
+       OutPoint { inner: ObjOps::heap_alloc(nativeOutPoint {
                txid: ::bitcoin::hash_types::Txid::from_slice(&txid_arg.data[..]).unwrap(),
                index: index_arg,
-       })), is_owned: true }
+       }), is_owned: true }
 }
 impl Clone for OutPoint {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeOutPoint>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -118,7 +124,7 @@ pub extern "C" fn OutPoint_clone(orig: &OutPoint) -> OutPoint {
 pub extern "C" fn OutPoint_eq(a: &OutPoint, b: &OutPoint) -> bool {
        if a.inner == b.inner { return true; }
        if a.inner.is_null() || b.inner.is_null() { return false; }
-       if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false }
+       if a.get_native_ref() == b.get_native_ref() { true } else { false }
 }
 /// Checks if two OutPoints contain equal inner contents.
 #[no_mangle]
@@ -127,21 +133,21 @@ pub extern "C" fn OutPoint_hash(o: &OutPoint) -> u64 {
        // Note that we'd love to use std::collections::hash_map::DefaultHasher but it's not in core
        #[allow(deprecated)]
        let mut hasher = core::hash::SipHasher::new();
-       std::hash::Hash::hash(unsafe { &*o.inner }, &mut hasher);
+       std::hash::Hash::hash(o.get_native_ref(), &mut hasher);
        std::hash::Hasher::finish(&hasher)
 }
 /// Convert an `OutPoint` to a lightning channel id.
 #[must_use]
 #[no_mangle]
 pub extern "C" fn OutPoint_to_channel_id(this_arg: &OutPoint) -> crate::c_types::ThirtyTwoBytes {
-       let mut ret = unsafe { &*this_arg.inner }.to_channel_id();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.to_channel_id();
        crate::c_types::ThirtyTwoBytes { data: ret }
 }
 
 #[no_mangle]
 /// Serialize the OutPoint object into a byte array which can be read by OutPoint_read
 pub extern "C" fn OutPoint_write(obj: &OutPoint) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }
 #[no_mangle]
 pub(crate) extern "C" fn OutPoint_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
@@ -151,6 +157,6 @@ pub(crate) extern "C" fn OutPoint_write_void(obj: *const c_void) -> crate::c_typ
 /// Read a OutPoint from a byte array, created by OutPoint_write
 pub extern "C" fn OutPoint_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_OutPointDecodeErrorZ {
        let res = crate::c_types::deserialize_obj(ser);
-       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_res
 }
index 5cf8b63069a6870372c370ff85ef4e49b7b9b922..0fa8612da83a6e50745dd742e67c2fa529fc6bda 100644 (file)
@@ -113,7 +113,7 @@ pub struct TxCreationKeys {
 impl Drop for TxCreationKeys {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeTxCreationKeys>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -126,11 +126,17 @@ extern "C" fn TxCreationKeys_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeTxCreationKeys); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl TxCreationKeys {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeTxCreationKeys {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeTxCreationKeys {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeTxCreationKeys {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -138,20 +144,20 @@ impl TxCreationKeys {
 /// The broadcaster's per-commitment public key which was used to derive the other keys.
 #[no_mangle]
 pub extern "C" fn TxCreationKeys_get_per_commitment_point(this_ptr: &TxCreationKeys) -> crate::c_types::PublicKey {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.per_commitment_point;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().per_commitment_point;
        crate::c_types::PublicKey::from_rust(&inner_val)
 }
 /// The broadcaster's per-commitment public key which was used to derive the other keys.
 #[no_mangle]
 pub extern "C" fn TxCreationKeys_set_per_commitment_point(this_ptr: &mut TxCreationKeys, mut val: crate::c_types::PublicKey) {
-       unsafe { &mut *this_ptr.inner }.per_commitment_point = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.per_commitment_point = val.into_rust();
 }
 /// The revocation key which is used to allow the broadcaster of the commitment
 /// transaction to provide their counterparty the ability to punish them if they broadcast
 /// an old state.
 #[no_mangle]
 pub extern "C" fn TxCreationKeys_get_revocation_key(this_ptr: &TxCreationKeys) -> crate::c_types::PublicKey {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.revocation_key;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().revocation_key;
        crate::c_types::PublicKey::from_rust(&inner_val)
 }
 /// The revocation key which is used to allow the broadcaster of the commitment
@@ -159,58 +165,58 @@ pub extern "C" fn TxCreationKeys_get_revocation_key(this_ptr: &TxCreationKeys) -
 /// an old state.
 #[no_mangle]
 pub extern "C" fn TxCreationKeys_set_revocation_key(this_ptr: &mut TxCreationKeys, mut val: crate::c_types::PublicKey) {
-       unsafe { &mut *this_ptr.inner }.revocation_key = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.revocation_key = val.into_rust();
 }
 /// Broadcaster's HTLC Key
 #[no_mangle]
 pub extern "C" fn TxCreationKeys_get_broadcaster_htlc_key(this_ptr: &TxCreationKeys) -> crate::c_types::PublicKey {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.broadcaster_htlc_key;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().broadcaster_htlc_key;
        crate::c_types::PublicKey::from_rust(&inner_val)
 }
 /// Broadcaster's HTLC Key
 #[no_mangle]
 pub extern "C" fn TxCreationKeys_set_broadcaster_htlc_key(this_ptr: &mut TxCreationKeys, mut val: crate::c_types::PublicKey) {
-       unsafe { &mut *this_ptr.inner }.broadcaster_htlc_key = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.broadcaster_htlc_key = val.into_rust();
 }
 /// Countersignatory's HTLC Key
 #[no_mangle]
 pub extern "C" fn TxCreationKeys_get_countersignatory_htlc_key(this_ptr: &TxCreationKeys) -> crate::c_types::PublicKey {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.countersignatory_htlc_key;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().countersignatory_htlc_key;
        crate::c_types::PublicKey::from_rust(&inner_val)
 }
 /// Countersignatory's HTLC Key
 #[no_mangle]
 pub extern "C" fn TxCreationKeys_set_countersignatory_htlc_key(this_ptr: &mut TxCreationKeys, mut val: crate::c_types::PublicKey) {
-       unsafe { &mut *this_ptr.inner }.countersignatory_htlc_key = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.countersignatory_htlc_key = val.into_rust();
 }
 /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
 #[no_mangle]
 pub extern "C" fn TxCreationKeys_get_broadcaster_delayed_payment_key(this_ptr: &TxCreationKeys) -> crate::c_types::PublicKey {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.broadcaster_delayed_payment_key;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().broadcaster_delayed_payment_key;
        crate::c_types::PublicKey::from_rust(&inner_val)
 }
 /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay)
 #[no_mangle]
 pub extern "C" fn TxCreationKeys_set_broadcaster_delayed_payment_key(this_ptr: &mut TxCreationKeys, mut val: crate::c_types::PublicKey) {
-       unsafe { &mut *this_ptr.inner }.broadcaster_delayed_payment_key = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.broadcaster_delayed_payment_key = val.into_rust();
 }
 /// Constructs a new TxCreationKeys given each field
 #[must_use]
 #[no_mangle]
 pub extern "C" fn TxCreationKeys_new(mut per_commitment_point_arg: crate::c_types::PublicKey, mut revocation_key_arg: crate::c_types::PublicKey, mut broadcaster_htlc_key_arg: crate::c_types::PublicKey, mut countersignatory_htlc_key_arg: crate::c_types::PublicKey, mut broadcaster_delayed_payment_key_arg: crate::c_types::PublicKey) -> TxCreationKeys {
-       TxCreationKeys { inner: Box::into_raw(Box::new(nativeTxCreationKeys {
+       TxCreationKeys { inner: ObjOps::heap_alloc(nativeTxCreationKeys {
                per_commitment_point: per_commitment_point_arg.into_rust(),
                revocation_key: revocation_key_arg.into_rust(),
                broadcaster_htlc_key: broadcaster_htlc_key_arg.into_rust(),
                countersignatory_htlc_key: countersignatory_htlc_key_arg.into_rust(),
                broadcaster_delayed_payment_key: broadcaster_delayed_payment_key_arg.into_rust(),
-       })), is_owned: true }
+       }), is_owned: true }
 }
 impl Clone for TxCreationKeys {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeTxCreationKeys>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -228,7 +234,7 @@ pub extern "C" fn TxCreationKeys_clone(orig: &TxCreationKeys) -> TxCreationKeys
 #[no_mangle]
 /// Serialize the TxCreationKeys object into a byte array which can be read by TxCreationKeys_read
 pub extern "C" fn TxCreationKeys_write(obj: &TxCreationKeys) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }
 #[no_mangle]
 pub(crate) extern "C" fn TxCreationKeys_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
@@ -238,7 +244,7 @@ pub(crate) extern "C" fn TxCreationKeys_write_void(obj: *const c_void) -> crate:
 /// Read a TxCreationKeys from a byte array, created by TxCreationKeys_write
 pub extern "C" fn TxCreationKeys_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_TxCreationKeysDecodeErrorZ {
        let res = crate::c_types::deserialize_obj(ser);
-       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TxCreationKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TxCreationKeys { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_res
 }
 
@@ -264,7 +270,7 @@ pub struct ChannelPublicKeys {
 impl Drop for ChannelPublicKeys {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeChannelPublicKeys>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -277,11 +283,17 @@ extern "C" fn ChannelPublicKeys_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelPublicKeys); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelPublicKeys {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeChannelPublicKeys {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelPublicKeys {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeChannelPublicKeys {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -290,14 +302,14 @@ impl ChannelPublicKeys {
 /// on-chain channel lock-in 2-of-2 multisig output.
 #[no_mangle]
 pub extern "C" fn ChannelPublicKeys_get_funding_pubkey(this_ptr: &ChannelPublicKeys) -> crate::c_types::PublicKey {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_pubkey;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().funding_pubkey;
        crate::c_types::PublicKey::from_rust(&inner_val)
 }
 /// The public key which is used to sign all commitment transactions, as it appears in the
 /// on-chain channel lock-in 2-of-2 multisig output.
 #[no_mangle]
 pub extern "C" fn ChannelPublicKeys_set_funding_pubkey(this_ptr: &mut ChannelPublicKeys, mut val: crate::c_types::PublicKey) {
-       unsafe { &mut *this_ptr.inner }.funding_pubkey = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.funding_pubkey = val.into_rust();
 }
 /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
 /// revocation keys. This is combined with the per-commitment-secret generated by the
@@ -305,7 +317,7 @@ pub extern "C" fn ChannelPublicKeys_set_funding_pubkey(this_ptr: &mut ChannelPub
 /// states.
 #[no_mangle]
 pub extern "C" fn ChannelPublicKeys_get_revocation_basepoint(this_ptr: &ChannelPublicKeys) -> crate::c_types::PublicKey {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.revocation_basepoint;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().revocation_basepoint;
        crate::c_types::PublicKey::from_rust(&inner_val)
 }
 /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
@@ -314,14 +326,14 @@ pub extern "C" fn ChannelPublicKeys_get_revocation_basepoint(this_ptr: &ChannelP
 /// states.
 #[no_mangle]
 pub extern "C" fn ChannelPublicKeys_set_revocation_basepoint(this_ptr: &mut ChannelPublicKeys, mut val: crate::c_types::PublicKey) {
-       unsafe { &mut *this_ptr.inner }.revocation_basepoint = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.revocation_basepoint = val.into_rust();
 }
 /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
 /// spendable primary channel balance on the broadcaster's commitment transaction. This key is
 /// static across every commitment transaction.
 #[no_mangle]
 pub extern "C" fn ChannelPublicKeys_get_payment_point(this_ptr: &ChannelPublicKeys) -> crate::c_types::PublicKey {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.payment_point;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().payment_point;
        crate::c_types::PublicKey::from_rust(&inner_val)
 }
 /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately
@@ -329,14 +341,14 @@ pub extern "C" fn ChannelPublicKeys_get_payment_point(this_ptr: &ChannelPublicKe
 /// static across every commitment transaction.
 #[no_mangle]
 pub extern "C" fn ChannelPublicKeys_set_payment_point(this_ptr: &mut ChannelPublicKeys, mut val: crate::c_types::PublicKey) {
-       unsafe { &mut *this_ptr.inner }.payment_point = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.payment_point = val.into_rust();
 }
 /// The base point which is used (with derive_public_key) to derive a per-commitment payment
 /// public key which receives non-HTLC-encumbered funds which are only available for spending
 /// after some delay (or can be claimed via the revocation path).
 #[no_mangle]
 pub extern "C" fn ChannelPublicKeys_get_delayed_payment_basepoint(this_ptr: &ChannelPublicKeys) -> crate::c_types::PublicKey {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.delayed_payment_basepoint;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().delayed_payment_basepoint;
        crate::c_types::PublicKey::from_rust(&inner_val)
 }
 /// The base point which is used (with derive_public_key) to derive a per-commitment payment
@@ -344,38 +356,38 @@ pub extern "C" fn ChannelPublicKeys_get_delayed_payment_basepoint(this_ptr: &Cha
 /// after some delay (or can be claimed via the revocation path).
 #[no_mangle]
 pub extern "C" fn ChannelPublicKeys_set_delayed_payment_basepoint(this_ptr: &mut ChannelPublicKeys, mut val: crate::c_types::PublicKey) {
-       unsafe { &mut *this_ptr.inner }.delayed_payment_basepoint = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.delayed_payment_basepoint = val.into_rust();
 }
 /// The base point which is used (with derive_public_key) to derive a per-commitment public key
 /// which is used to encumber HTLC-in-flight outputs.
 #[no_mangle]
 pub extern "C" fn ChannelPublicKeys_get_htlc_basepoint(this_ptr: &ChannelPublicKeys) -> crate::c_types::PublicKey {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_basepoint;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().htlc_basepoint;
        crate::c_types::PublicKey::from_rust(&inner_val)
 }
 /// The base point which is used (with derive_public_key) to derive a per-commitment public key
 /// which is used to encumber HTLC-in-flight outputs.
 #[no_mangle]
 pub extern "C" fn ChannelPublicKeys_set_htlc_basepoint(this_ptr: &mut ChannelPublicKeys, mut val: crate::c_types::PublicKey) {
-       unsafe { &mut *this_ptr.inner }.htlc_basepoint = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_basepoint = val.into_rust();
 }
 /// Constructs a new ChannelPublicKeys given each field
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelPublicKeys_new(mut funding_pubkey_arg: crate::c_types::PublicKey, mut revocation_basepoint_arg: crate::c_types::PublicKey, mut payment_point_arg: crate::c_types::PublicKey, mut delayed_payment_basepoint_arg: crate::c_types::PublicKey, mut htlc_basepoint_arg: crate::c_types::PublicKey) -> ChannelPublicKeys {
-       ChannelPublicKeys { inner: Box::into_raw(Box::new(nativeChannelPublicKeys {
+       ChannelPublicKeys { inner: ObjOps::heap_alloc(nativeChannelPublicKeys {
                funding_pubkey: funding_pubkey_arg.into_rust(),
                revocation_basepoint: revocation_basepoint_arg.into_rust(),
                payment_point: payment_point_arg.into_rust(),
                delayed_payment_basepoint: delayed_payment_basepoint_arg.into_rust(),
                htlc_basepoint: htlc_basepoint_arg.into_rust(),
-       })), is_owned: true }
+       }), is_owned: true }
 }
 impl Clone for ChannelPublicKeys {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeChannelPublicKeys>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -393,7 +405,7 @@ pub extern "C" fn ChannelPublicKeys_clone(orig: &ChannelPublicKeys) -> ChannelPu
 #[no_mangle]
 /// Serialize the ChannelPublicKeys object into a byte array which can be read by ChannelPublicKeys_read
 pub extern "C" fn ChannelPublicKeys_write(obj: &ChannelPublicKeys) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }
 #[no_mangle]
 pub(crate) extern "C" fn ChannelPublicKeys_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
@@ -403,7 +415,7 @@ pub(crate) extern "C" fn ChannelPublicKeys_write_void(obj: *const c_void) -> cra
 /// Read a ChannelPublicKeys from a byte array, created by ChannelPublicKeys_write
 pub extern "C" fn ChannelPublicKeys_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelPublicKeysDecodeErrorZ {
        let res = crate::c_types::deserialize_obj(ser);
-       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_res
 }
 /// Create per-state keys from channel base points and the per-commitment point.
@@ -412,7 +424,7 @@ pub extern "C" fn ChannelPublicKeys_read(ser: crate::c_types::u8slice) -> crate:
 #[no_mangle]
 pub extern "C" fn TxCreationKeys_derive_new(mut per_commitment_point: crate::c_types::PublicKey, mut broadcaster_delayed_payment_base: crate::c_types::PublicKey, mut broadcaster_htlc_base: crate::c_types::PublicKey, mut countersignatory_revocation_base: crate::c_types::PublicKey, mut countersignatory_htlc_base: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_TxCreationKeysErrorZ {
        let mut ret = lightning::ln::chan_utils::TxCreationKeys::derive_new(secp256k1::SECP256K1, &per_commitment_point.into_rust(), &broadcaster_delayed_payment_base.into_rust(), &broadcaster_htlc_base.into_rust(), &countersignatory_revocation_base.into_rust(), &countersignatory_htlc_base.into_rust());
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TxCreationKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() };
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TxCreationKeys { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() };
        local_ret
 }
 
@@ -421,8 +433,8 @@ pub extern "C" fn TxCreationKeys_derive_new(mut per_commitment_point: crate::c_t
 #[must_use]
 #[no_mangle]
 pub extern "C" fn TxCreationKeys_from_channel_static_keys(mut per_commitment_point: crate::c_types::PublicKey, broadcaster_keys: &crate::lightning::ln::chan_utils::ChannelPublicKeys, countersignatory_keys: &crate::lightning::ln::chan_utils::ChannelPublicKeys) -> crate::c_types::derived::CResult_TxCreationKeysErrorZ {
-       let mut ret = lightning::ln::chan_utils::TxCreationKeys::from_channel_static_keys(&per_commitment_point.into_rust(), unsafe { &*broadcaster_keys.inner }, unsafe { &*countersignatory_keys.inner }, secp256k1::SECP256K1);
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TxCreationKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() };
+       let mut ret = lightning::ln::chan_utils::TxCreationKeys::from_channel_static_keys(&per_commitment_point.into_rust(), broadcaster_keys.get_native_ref(), countersignatory_keys.get_native_ref(), secp256k1::SECP256K1);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TxCreationKeys { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() };
        local_ret
 }
 
@@ -462,7 +474,7 @@ pub struct HTLCOutputInCommitment {
 impl Drop for HTLCOutputInCommitment {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeHTLCOutputInCommitment>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -475,11 +487,17 @@ extern "C" fn HTLCOutputInCommitment_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeHTLCOutputInCommitment); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl HTLCOutputInCommitment {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeHTLCOutputInCommitment {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeHTLCOutputInCommitment {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeHTLCOutputInCommitment {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -490,7 +508,7 @@ impl HTLCOutputInCommitment {
 /// the counterparty or our own.
 #[no_mangle]
 pub extern "C" fn HTLCOutputInCommitment_get_offered(this_ptr: &HTLCOutputInCommitment) -> bool {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.offered;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().offered;
        *inner_val
 }
 /// Whether the HTLC was \"offered\" (ie outbound in relation to this commitment transaction).
@@ -499,49 +517,49 @@ pub extern "C" fn HTLCOutputInCommitment_get_offered(this_ptr: &HTLCOutputInComm
 /// the counterparty or our own.
 #[no_mangle]
 pub extern "C" fn HTLCOutputInCommitment_set_offered(this_ptr: &mut HTLCOutputInCommitment, mut val: bool) {
-       unsafe { &mut *this_ptr.inner }.offered = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.offered = val;
 }
 /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
 /// this divided by 1000.
 #[no_mangle]
 pub extern "C" fn HTLCOutputInCommitment_get_amount_msat(this_ptr: &HTLCOutputInCommitment) -> u64 {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.amount_msat;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().amount_msat;
        *inner_val
 }
 /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
 /// this divided by 1000.
 #[no_mangle]
 pub extern "C" fn HTLCOutputInCommitment_set_amount_msat(this_ptr: &mut HTLCOutputInCommitment, mut val: u64) {
-       unsafe { &mut *this_ptr.inner }.amount_msat = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.amount_msat = val;
 }
 /// The CLTV lock-time at which this HTLC expires.
 #[no_mangle]
 pub extern "C" fn HTLCOutputInCommitment_get_cltv_expiry(this_ptr: &HTLCOutputInCommitment) -> u32 {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.cltv_expiry;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().cltv_expiry;
        *inner_val
 }
 /// The CLTV lock-time at which this HTLC expires.
 #[no_mangle]
 pub extern "C" fn HTLCOutputInCommitment_set_cltv_expiry(this_ptr: &mut HTLCOutputInCommitment, mut val: u32) {
-       unsafe { &mut *this_ptr.inner }.cltv_expiry = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.cltv_expiry = val;
 }
 /// The hash of the preimage which unlocks this HTLC.
 #[no_mangle]
 pub extern "C" fn HTLCOutputInCommitment_get_payment_hash(this_ptr: &HTLCOutputInCommitment) -> *const [u8; 32] {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.payment_hash;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().payment_hash;
        &inner_val.0
 }
 /// The hash of the preimage which unlocks this HTLC.
 #[no_mangle]
 pub extern "C" fn HTLCOutputInCommitment_set_payment_hash(this_ptr: &mut HTLCOutputInCommitment, mut val: crate::c_types::ThirtyTwoBytes) {
-       unsafe { &mut *this_ptr.inner }.payment_hash = ::lightning::ln::PaymentHash(val.data);
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.payment_hash = ::lightning::ln::PaymentHash(val.data);
 }
 /// The position within the commitment transactions' outputs. This may be None if the value is
 /// below the dust limit (in which case no output appears in the commitment transaction and the
 /// value is spent to additional transaction fees).
 #[no_mangle]
 pub extern "C" fn HTLCOutputInCommitment_get_transaction_output_index(this_ptr: &HTLCOutputInCommitment) -> crate::c_types::derived::COption_u32Z {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.transaction_output_index;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().transaction_output_index;
        let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u32Z::None } else {  { crate::c_types::derived::COption_u32Z::Some(inner_val.unwrap()) } };
        local_inner_val
 }
@@ -551,26 +569,26 @@ pub extern "C" fn HTLCOutputInCommitment_get_transaction_output_index(this_ptr:
 #[no_mangle]
 pub extern "C" fn HTLCOutputInCommitment_set_transaction_output_index(this_ptr: &mut HTLCOutputInCommitment, mut val: crate::c_types::derived::COption_u32Z) {
        let mut local_val = if val.is_some() { Some( { val.take() }) } else { None };
-       unsafe { &mut *this_ptr.inner }.transaction_output_index = local_val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.transaction_output_index = local_val;
 }
 /// Constructs a new HTLCOutputInCommitment given each field
 #[must_use]
 #[no_mangle]
 pub extern "C" fn HTLCOutputInCommitment_new(mut offered_arg: bool, mut amount_msat_arg: u64, mut cltv_expiry_arg: u32, mut payment_hash_arg: crate::c_types::ThirtyTwoBytes, mut transaction_output_index_arg: crate::c_types::derived::COption_u32Z) -> HTLCOutputInCommitment {
        let mut local_transaction_output_index_arg = if transaction_output_index_arg.is_some() { Some( { transaction_output_index_arg.take() }) } else { None };
-       HTLCOutputInCommitment { inner: Box::into_raw(Box::new(nativeHTLCOutputInCommitment {
+       HTLCOutputInCommitment { inner: ObjOps::heap_alloc(nativeHTLCOutputInCommitment {
                offered: offered_arg,
                amount_msat: amount_msat_arg,
                cltv_expiry: cltv_expiry_arg,
                payment_hash: ::lightning::ln::PaymentHash(payment_hash_arg.data),
                transaction_output_index: local_transaction_output_index_arg,
-       })), is_owned: true }
+       }), is_owned: true }
 }
 impl Clone for HTLCOutputInCommitment {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeHTLCOutputInCommitment>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -588,7 +606,7 @@ pub extern "C" fn HTLCOutputInCommitment_clone(orig: &HTLCOutputInCommitment) ->
 #[no_mangle]
 /// Serialize the HTLCOutputInCommitment object into a byte array which can be read by HTLCOutputInCommitment_read
 pub extern "C" fn HTLCOutputInCommitment_write(obj: &HTLCOutputInCommitment) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }
 #[no_mangle]
 pub(crate) extern "C" fn HTLCOutputInCommitment_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
@@ -598,14 +616,14 @@ pub(crate) extern "C" fn HTLCOutputInCommitment_write_void(obj: *const c_void) -
 /// Read a HTLCOutputInCommitment from a byte array, created by HTLCOutputInCommitment_write
 pub extern "C" fn HTLCOutputInCommitment_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_HTLCOutputInCommitmentDecodeErrorZ {
        let res = crate::c_types::deserialize_obj(ser);
-       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_res
 }
 /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc
 /// does not need to have its previous_output_index filled.
 #[no_mangle]
 pub extern "C" fn get_htlc_redeemscript(htlc: &crate::lightning::ln::chan_utils::HTLCOutputInCommitment, keys: &crate::lightning::ln::chan_utils::TxCreationKeys) -> crate::c_types::derived::CVec_u8Z {
-       let mut ret = lightning::ln::chan_utils::get_htlc_redeemscript(unsafe { &*htlc.inner }, unsafe { &*keys.inner });
+       let mut ret = lightning::ln::chan_utils::get_htlc_redeemscript(htlc.get_native_ref(), keys.get_native_ref());
        ret.into_bytes().into()
 }
 
@@ -626,7 +644,7 @@ pub extern "C" fn make_funding_redeemscript(mut broadcaster: crate::c_types::Pub
 /// commitment transaction).
 #[no_mangle]
 pub extern "C" fn build_htlc_transaction(commitment_txid: *const [u8; 32], mut feerate_per_kw: u32, mut contest_delay: u16, htlc: &crate::lightning::ln::chan_utils::HTLCOutputInCommitment, mut broadcaster_delayed_payment_key: crate::c_types::PublicKey, mut revocation_key: crate::c_types::PublicKey) -> crate::c_types::Transaction {
-       let mut ret = lightning::ln::chan_utils::build_htlc_transaction(&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*commitment_txid }[..]).unwrap(), feerate_per_kw, contest_delay, unsafe { &*htlc.inner }, &broadcaster_delayed_payment_key.into_rust(), &revocation_key.into_rust());
+       let mut ret = lightning::ln::chan_utils::build_htlc_transaction(&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*commitment_txid }[..]).unwrap(), feerate_per_kw, contest_delay, htlc.get_native_ref(), &broadcaster_delayed_payment_key.into_rust(), &revocation_key.into_rust());
        crate::c_types::Transaction::from_bitcoin(&ret)
 }
 
@@ -657,7 +675,7 @@ pub struct ChannelTransactionParameters {
 impl Drop for ChannelTransactionParameters {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeChannelTransactionParameters>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -670,11 +688,17 @@ extern "C" fn ChannelTransactionParameters_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelTransactionParameters); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelTransactionParameters {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeChannelTransactionParameters {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelTransactionParameters {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeChannelTransactionParameters {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -682,37 +706,37 @@ impl ChannelTransactionParameters {
 /// Holder public keys
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_get_holder_pubkeys(this_ptr: &ChannelTransactionParameters) -> crate::lightning::ln::chan_utils::ChannelPublicKeys {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.holder_pubkeys;
-       crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false }
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().holder_pubkeys;
+       crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false }
 }
 /// Holder public keys
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_set_holder_pubkeys(this_ptr: &mut ChannelTransactionParameters, mut val: crate::lightning::ln::chan_utils::ChannelPublicKeys) {
-       unsafe { &mut *this_ptr.inner }.holder_pubkeys = *unsafe { Box::from_raw(val.take_inner()) };
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.holder_pubkeys = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_get_holder_selected_contest_delay(this_ptr: &ChannelTransactionParameters) -> u16 {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.holder_selected_contest_delay;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().holder_selected_contest_delay;
        *inner_val
 }
 /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_set_holder_selected_contest_delay(this_ptr: &mut ChannelTransactionParameters, mut val: u16) {
-       unsafe { &mut *this_ptr.inner }.holder_selected_contest_delay = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.holder_selected_contest_delay = val;
 }
 /// Whether the holder is the initiator of this channel.
 /// This is an input to the commitment number obscure factor computation.
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_get_is_outbound_from_holder(this_ptr: &ChannelTransactionParameters) -> bool {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.is_outbound_from_holder;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().is_outbound_from_holder;
        *inner_val
 }
 /// Whether the holder is the initiator of this channel.
 /// This is an input to the commitment number obscure factor computation.
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_set_is_outbound_from_holder(this_ptr: &mut ChannelTransactionParameters, mut val: bool) {
-       unsafe { &mut *this_ptr.inner }.is_outbound_from_holder = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.is_outbound_from_holder = val;
 }
 /// The late-bound counterparty channel transaction parameters.
 /// These parameters are populated at the point in the protocol where the counterparty provides them.
@@ -720,8 +744,8 @@ pub extern "C" fn ChannelTransactionParameters_set_is_outbound_from_holder(this_
 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_get_counterparty_parameters(this_ptr: &ChannelTransactionParameters) -> crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.counterparty_parameters;
-       let mut local_inner_val = crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else {  { (inner_val.as_ref().unwrap()) } } as *const _) as *mut _ }, is_owned: false };
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().counterparty_parameters;
+       let mut local_inner_val = crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const _) as *mut _ }, is_owned: false };
        local_inner_val
 }
 /// The late-bound counterparty channel transaction parameters.
@@ -731,15 +755,15 @@ pub extern "C" fn ChannelTransactionParameters_get_counterparty_parameters(this_
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_set_counterparty_parameters(this_ptr: &mut ChannelTransactionParameters, mut val: crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters) {
        let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
-       unsafe { &mut *this_ptr.inner }.counterparty_parameters = local_val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.counterparty_parameters = local_val;
 }
 /// The late-bound funding outpoint
 ///
 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_get_funding_outpoint(this_ptr: &ChannelTransactionParameters) -> crate::lightning::chain::transaction::OutPoint {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_outpoint;
-       let mut local_inner_val = crate::lightning::chain::transaction::OutPoint { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else {  { (inner_val.as_ref().unwrap()) } } as *const _) as *mut _ }, is_owned: false };
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().funding_outpoint;
+       let mut local_inner_val = crate::lightning::chain::transaction::OutPoint { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const _) as *mut _ }, is_owned: false };
        local_inner_val
 }
 /// The late-bound funding outpoint
@@ -748,7 +772,7 @@ pub extern "C" fn ChannelTransactionParameters_get_funding_outpoint(this_ptr: &C
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_set_funding_outpoint(this_ptr: &mut ChannelTransactionParameters, mut val: crate::lightning::chain::transaction::OutPoint) {
        let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
-       unsafe { &mut *this_ptr.inner }.funding_outpoint = local_val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.funding_outpoint = local_val;
 }
 /// Constructs a new ChannelTransactionParameters given each field
 #[must_use]
@@ -756,19 +780,19 @@ pub extern "C" fn ChannelTransactionParameters_set_funding_outpoint(this_ptr: &m
 pub extern "C" fn ChannelTransactionParameters_new(mut holder_pubkeys_arg: crate::lightning::ln::chan_utils::ChannelPublicKeys, mut holder_selected_contest_delay_arg: u16, mut is_outbound_from_holder_arg: bool, mut counterparty_parameters_arg: crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters, mut funding_outpoint_arg: crate::lightning::chain::transaction::OutPoint) -> ChannelTransactionParameters {
        let mut local_counterparty_parameters_arg = if counterparty_parameters_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(counterparty_parameters_arg.take_inner()) } }) };
        let mut local_funding_outpoint_arg = if funding_outpoint_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(funding_outpoint_arg.take_inner()) } }) };
-       ChannelTransactionParameters { inner: Box::into_raw(Box::new(nativeChannelTransactionParameters {
+       ChannelTransactionParameters { inner: ObjOps::heap_alloc(nativeChannelTransactionParameters {
                holder_pubkeys: *unsafe { Box::from_raw(holder_pubkeys_arg.take_inner()) },
                holder_selected_contest_delay: holder_selected_contest_delay_arg,
                is_outbound_from_holder: is_outbound_from_holder_arg,
                counterparty_parameters: local_counterparty_parameters_arg,
                funding_outpoint: local_funding_outpoint_arg,
-       })), is_owned: true }
+       }), is_owned: true }
 }
 impl Clone for ChannelTransactionParameters {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeChannelTransactionParameters>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -806,7 +830,7 @@ pub struct CounterpartyChannelTransactionParameters {
 impl Drop for CounterpartyChannelTransactionParameters {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeCounterpartyChannelTransactionParameters>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -819,11 +843,17 @@ extern "C" fn CounterpartyChannelTransactionParameters_free_void(this_ptr: *mut
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeCounterpartyChannelTransactionParameters); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl CounterpartyChannelTransactionParameters {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeCounterpartyChannelTransactionParameters {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeCounterpartyChannelTransactionParameters {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeCounterpartyChannelTransactionParameters {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -831,39 +861,39 @@ impl CounterpartyChannelTransactionParameters {
 /// Counter-party public keys
 #[no_mangle]
 pub extern "C" fn CounterpartyChannelTransactionParameters_get_pubkeys(this_ptr: &CounterpartyChannelTransactionParameters) -> crate::lightning::ln::chan_utils::ChannelPublicKeys {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.pubkeys;
-       crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false }
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().pubkeys;
+       crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false }
 }
 /// Counter-party public keys
 #[no_mangle]
 pub extern "C" fn CounterpartyChannelTransactionParameters_set_pubkeys(this_ptr: &mut CounterpartyChannelTransactionParameters, mut val: crate::lightning::ln::chan_utils::ChannelPublicKeys) {
-       unsafe { &mut *this_ptr.inner }.pubkeys = *unsafe { Box::from_raw(val.take_inner()) };
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.pubkeys = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
 #[no_mangle]
 pub extern "C" fn CounterpartyChannelTransactionParameters_get_selected_contest_delay(this_ptr: &CounterpartyChannelTransactionParameters) -> u16 {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.selected_contest_delay;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().selected_contest_delay;
        *inner_val
 }
 /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions
 #[no_mangle]
 pub extern "C" fn CounterpartyChannelTransactionParameters_set_selected_contest_delay(this_ptr: &mut CounterpartyChannelTransactionParameters, mut val: u16) {
-       unsafe { &mut *this_ptr.inner }.selected_contest_delay = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.selected_contest_delay = val;
 }
 /// Constructs a new CounterpartyChannelTransactionParameters given each field
 #[must_use]
 #[no_mangle]
 pub extern "C" fn CounterpartyChannelTransactionParameters_new(mut pubkeys_arg: crate::lightning::ln::chan_utils::ChannelPublicKeys, mut selected_contest_delay_arg: u16) -> CounterpartyChannelTransactionParameters {
-       CounterpartyChannelTransactionParameters { inner: Box::into_raw(Box::new(nativeCounterpartyChannelTransactionParameters {
+       CounterpartyChannelTransactionParameters { inner: ObjOps::heap_alloc(nativeCounterpartyChannelTransactionParameters {
                pubkeys: *unsafe { Box::from_raw(pubkeys_arg.take_inner()) },
                selected_contest_delay: selected_contest_delay_arg,
-       })), is_owned: true }
+       }), is_owned: true }
 }
 impl Clone for CounterpartyChannelTransactionParameters {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeCounterpartyChannelTransactionParameters>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -882,7 +912,7 @@ pub extern "C" fn CounterpartyChannelTransactionParameters_clone(orig: &Counterp
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_is_populated(this_arg: &ChannelTransactionParameters) -> bool {
-       let mut ret = unsafe { &*this_arg.inner }.is_populated();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_populated();
        ret
 }
 
@@ -893,8 +923,8 @@ pub extern "C" fn ChannelTransactionParameters_is_populated(this_arg: &ChannelTr
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_as_holder_broadcastable(this_arg: &ChannelTransactionParameters) -> crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters {
-       let mut ret = unsafe { &*this_arg.inner }.as_holder_broadcastable();
-       crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.as_holder_broadcastable();
+       crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
@@ -904,14 +934,14 @@ pub extern "C" fn ChannelTransactionParameters_as_holder_broadcastable(this_arg:
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_as_counterparty_broadcastable(this_arg: &ChannelTransactionParameters) -> crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters {
-       let mut ret = unsafe { &*this_arg.inner }.as_counterparty_broadcastable();
-       crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.as_counterparty_broadcastable();
+       crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 #[no_mangle]
 /// Serialize the CounterpartyChannelTransactionParameters object into a byte array which can be read by CounterpartyChannelTransactionParameters_read
 pub extern "C" fn CounterpartyChannelTransactionParameters_write(obj: &CounterpartyChannelTransactionParameters) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }
 #[no_mangle]
 pub(crate) extern "C" fn CounterpartyChannelTransactionParameters_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
@@ -921,13 +951,13 @@ pub(crate) extern "C" fn CounterpartyChannelTransactionParameters_write_void(obj
 /// Read a CounterpartyChannelTransactionParameters from a byte array, created by CounterpartyChannelTransactionParameters_write
 pub extern "C" fn CounterpartyChannelTransactionParameters_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_CounterpartyChannelTransactionParametersDecodeErrorZ {
        let res = crate::c_types::deserialize_obj(ser);
-       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_res
 }
 #[no_mangle]
 /// Serialize the ChannelTransactionParameters object into a byte array which can be read by ChannelTransactionParameters_read
 pub extern "C" fn ChannelTransactionParameters_write(obj: &ChannelTransactionParameters) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }
 #[no_mangle]
 pub(crate) extern "C" fn ChannelTransactionParameters_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
@@ -937,7 +967,7 @@ pub(crate) extern "C" fn ChannelTransactionParameters_write_void(obj: *const c_v
 /// Read a ChannelTransactionParameters from a byte array, created by ChannelTransactionParameters_write
 pub extern "C" fn ChannelTransactionParameters_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelTransactionParametersDecodeErrorZ {
        let res = crate::c_types::deserialize_obj(ser);
-       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_res
 }
 
@@ -967,7 +997,7 @@ pub struct DirectedChannelTransactionParameters {
 impl Drop for DirectedChannelTransactionParameters {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeDirectedChannelTransactionParameters>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -980,11 +1010,17 @@ extern "C" fn DirectedChannelTransactionParameters_free_void(this_ptr: *mut c_vo
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeDirectedChannelTransactionParameters); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl DirectedChannelTransactionParameters {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeDirectedChannelTransactionParameters {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeDirectedChannelTransactionParameters {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeDirectedChannelTransactionParameters {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -993,16 +1029,16 @@ impl DirectedChannelTransactionParameters {
 #[must_use]
 #[no_mangle]
 pub extern "C" fn DirectedChannelTransactionParameters_broadcaster_pubkeys(this_arg: &DirectedChannelTransactionParameters) -> crate::lightning::ln::chan_utils::ChannelPublicKeys {
-       let mut ret = unsafe { &*this_arg.inner }.broadcaster_pubkeys();
-       crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.broadcaster_pubkeys();
+       crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false }
 }
 
 /// Get the channel pubkeys for the countersignatory
 #[must_use]
 #[no_mangle]
 pub extern "C" fn DirectedChannelTransactionParameters_countersignatory_pubkeys(this_arg: &DirectedChannelTransactionParameters) -> crate::lightning::ln::chan_utils::ChannelPublicKeys {
-       let mut ret = unsafe { &*this_arg.inner }.countersignatory_pubkeys();
-       crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.countersignatory_pubkeys();
+       crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false }
 }
 
 /// Get the contest delay applicable to the transactions.
@@ -1010,7 +1046,7 @@ pub extern "C" fn DirectedChannelTransactionParameters_countersignatory_pubkeys(
 #[must_use]
 #[no_mangle]
 pub extern "C" fn DirectedChannelTransactionParameters_contest_delay(this_arg: &DirectedChannelTransactionParameters) -> u16 {
-       let mut ret = unsafe { &*this_arg.inner }.contest_delay();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.contest_delay();
        ret
 }
 
@@ -1021,7 +1057,7 @@ pub extern "C" fn DirectedChannelTransactionParameters_contest_delay(this_arg: &
 #[must_use]
 #[no_mangle]
 pub extern "C" fn DirectedChannelTransactionParameters_is_outbound(this_arg: &DirectedChannelTransactionParameters) -> bool {
-       let mut ret = unsafe { &*this_arg.inner }.is_outbound();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_outbound();
        ret
 }
 
@@ -1029,7 +1065,7 @@ pub extern "C" fn DirectedChannelTransactionParameters_is_outbound(this_arg: &Di
 #[must_use]
 #[no_mangle]
 pub extern "C" fn DirectedChannelTransactionParameters_funding_outpoint(this_arg: &DirectedChannelTransactionParameters) -> crate::lightning::chain::transaction::OutPoint {
-       let mut ret = unsafe { &*this_arg.inner }.funding_outpoint();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.funding_outpoint();
        crate::c_types::bitcoin_to_C_outpoint(ret)
 }
 
@@ -1058,7 +1094,7 @@ pub struct HolderCommitmentTransaction {
 impl Drop for HolderCommitmentTransaction {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeHolderCommitmentTransaction>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -1071,11 +1107,17 @@ extern "C" fn HolderCommitmentTransaction_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeHolderCommitmentTransaction); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl HolderCommitmentTransaction {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeHolderCommitmentTransaction {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeHolderCommitmentTransaction {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeHolderCommitmentTransaction {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -1083,25 +1125,25 @@ impl HolderCommitmentTransaction {
 /// Our counterparty's signature for the transaction
 #[no_mangle]
 pub extern "C" fn HolderCommitmentTransaction_get_counterparty_sig(this_ptr: &HolderCommitmentTransaction) -> crate::c_types::Signature {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.counterparty_sig;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().counterparty_sig;
        crate::c_types::Signature::from_rust(&inner_val)
 }
 /// Our counterparty's signature for the transaction
 #[no_mangle]
 pub extern "C" fn HolderCommitmentTransaction_set_counterparty_sig(this_ptr: &mut HolderCommitmentTransaction, mut val: crate::c_types::Signature) {
-       unsafe { &mut *this_ptr.inner }.counterparty_sig = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.counterparty_sig = val.into_rust();
 }
 /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction
 #[no_mangle]
 pub extern "C" fn HolderCommitmentTransaction_set_counterparty_htlc_sigs(this_ptr: &mut HolderCommitmentTransaction, mut val: crate::c_types::derived::CVec_SignatureZ) {
        let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item.into_rust() }); };
-       unsafe { &mut *this_ptr.inner }.counterparty_htlc_sigs = local_val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.counterparty_htlc_sigs = local_val;
 }
 impl Clone for HolderCommitmentTransaction {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeHolderCommitmentTransaction>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -1119,7 +1161,7 @@ pub extern "C" fn HolderCommitmentTransaction_clone(orig: &HolderCommitmentTrans
 #[no_mangle]
 /// Serialize the HolderCommitmentTransaction object into a byte array which can be read by HolderCommitmentTransaction_read
 pub extern "C" fn HolderCommitmentTransaction_write(obj: &HolderCommitmentTransaction) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }
 #[no_mangle]
 pub(crate) extern "C" fn HolderCommitmentTransaction_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
@@ -1129,7 +1171,7 @@ pub(crate) extern "C" fn HolderCommitmentTransaction_write_void(obj: *const c_vo
 /// Read a HolderCommitmentTransaction from a byte array, created by HolderCommitmentTransaction_write
 pub extern "C" fn HolderCommitmentTransaction_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_HolderCommitmentTransactionDecodeErrorZ {
        let res = crate::c_types::deserialize_obj(ser);
-       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_res
 }
 /// Create a new holder transaction with the given counterparty signatures.
@@ -1139,7 +1181,7 @@ pub extern "C" fn HolderCommitmentTransaction_read(ser: crate::c_types::u8slice)
 pub extern "C" fn HolderCommitmentTransaction_new(mut commitment_tx: crate::lightning::ln::chan_utils::CommitmentTransaction, mut counterparty_sig: crate::c_types::Signature, mut counterparty_htlc_sigs: crate::c_types::derived::CVec_SignatureZ, mut holder_funding_key: crate::c_types::PublicKey, mut counterparty_funding_key: crate::c_types::PublicKey) -> HolderCommitmentTransaction {
        let mut local_counterparty_htlc_sigs = Vec::new(); for mut item in counterparty_htlc_sigs.into_rust().drain(..) { local_counterparty_htlc_sigs.push( { item.into_rust() }); };
        let mut ret = lightning::ln::chan_utils::HolderCommitmentTransaction::new(*unsafe { Box::from_raw(commitment_tx.take_inner()) }, counterparty_sig.into_rust(), local_counterparty_htlc_sigs, &holder_funding_key.into_rust(), &counterparty_funding_key.into_rust());
-       HolderCommitmentTransaction { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       HolderCommitmentTransaction { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 
@@ -1165,7 +1207,7 @@ pub struct BuiltCommitmentTransaction {
 impl Drop for BuiltCommitmentTransaction {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeBuiltCommitmentTransaction>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -1178,11 +1220,17 @@ extern "C" fn BuiltCommitmentTransaction_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeBuiltCommitmentTransaction); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl BuiltCommitmentTransaction {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeBuiltCommitmentTransaction {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBuiltCommitmentTransaction {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeBuiltCommitmentTransaction {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -1190,13 +1238,13 @@ impl BuiltCommitmentTransaction {
 /// The commitment transaction
 #[no_mangle]
 pub extern "C" fn BuiltCommitmentTransaction_get_transaction(this_ptr: &BuiltCommitmentTransaction) -> crate::c_types::Transaction {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.transaction;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().transaction;
        crate::c_types::Transaction::from_bitcoin(inner_val)
 }
 /// The commitment transaction
 #[no_mangle]
 pub extern "C" fn BuiltCommitmentTransaction_set_transaction(this_ptr: &mut BuiltCommitmentTransaction, mut val: crate::c_types::Transaction) {
-       unsafe { &mut *this_ptr.inner }.transaction = val.into_bitcoin();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.transaction = val.into_bitcoin();
 }
 /// The txid for the commitment transaction.
 ///
@@ -1204,7 +1252,7 @@ pub extern "C" fn BuiltCommitmentTransaction_set_transaction(this_ptr: &mut Buil
 /// multiple times.
 #[no_mangle]
 pub extern "C" fn BuiltCommitmentTransaction_get_txid(this_ptr: &BuiltCommitmentTransaction) -> *const [u8; 32] {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.txid;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().txid;
        inner_val.as_inner()
 }
 /// The txid for the commitment transaction.
@@ -1213,22 +1261,22 @@ pub extern "C" fn BuiltCommitmentTransaction_get_txid(this_ptr: &BuiltCommitment
 /// multiple times.
 #[no_mangle]
 pub extern "C" fn BuiltCommitmentTransaction_set_txid(this_ptr: &mut BuiltCommitmentTransaction, mut val: crate::c_types::ThirtyTwoBytes) {
-       unsafe { &mut *this_ptr.inner }.txid = ::bitcoin::hash_types::Txid::from_slice(&val.data[..]).unwrap();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.txid = ::bitcoin::hash_types::Txid::from_slice(&val.data[..]).unwrap();
 }
 /// Constructs a new BuiltCommitmentTransaction given each field
 #[must_use]
 #[no_mangle]
 pub extern "C" fn BuiltCommitmentTransaction_new(mut transaction_arg: crate::c_types::Transaction, mut txid_arg: crate::c_types::ThirtyTwoBytes) -> BuiltCommitmentTransaction {
-       BuiltCommitmentTransaction { inner: Box::into_raw(Box::new(nativeBuiltCommitmentTransaction {
+       BuiltCommitmentTransaction { inner: ObjOps::heap_alloc(nativeBuiltCommitmentTransaction {
                transaction: transaction_arg.into_bitcoin(),
                txid: ::bitcoin::hash_types::Txid::from_slice(&txid_arg.data[..]).unwrap(),
-       })), is_owned: true }
+       }), is_owned: true }
 }
 impl Clone for BuiltCommitmentTransaction {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeBuiltCommitmentTransaction>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -1246,7 +1294,7 @@ pub extern "C" fn BuiltCommitmentTransaction_clone(orig: &BuiltCommitmentTransac
 #[no_mangle]
 /// Serialize the BuiltCommitmentTransaction object into a byte array which can be read by BuiltCommitmentTransaction_read
 pub extern "C" fn BuiltCommitmentTransaction_write(obj: &BuiltCommitmentTransaction) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }
 #[no_mangle]
 pub(crate) extern "C" fn BuiltCommitmentTransaction_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
@@ -1256,7 +1304,7 @@ pub(crate) extern "C" fn BuiltCommitmentTransaction_write_void(obj: *const c_voi
 /// Read a BuiltCommitmentTransaction from a byte array, created by BuiltCommitmentTransaction_write
 pub extern "C" fn BuiltCommitmentTransaction_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_BuiltCommitmentTransactionDecodeErrorZ {
        let res = crate::c_types::deserialize_obj(ser);
-       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::BuiltCommitmentTransaction { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::BuiltCommitmentTransaction { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_res
 }
 /// Get the SIGHASH_ALL sighash value of the transaction.
@@ -1265,7 +1313,7 @@ pub extern "C" fn BuiltCommitmentTransaction_read(ser: crate::c_types::u8slice)
 #[must_use]
 #[no_mangle]
 pub extern "C" fn BuiltCommitmentTransaction_get_sighash_all(this_arg: &BuiltCommitmentTransaction, mut funding_redeemscript: crate::c_types::u8slice, mut channel_value_satoshis: u64) -> crate::c_types::ThirtyTwoBytes {
-       let mut ret = unsafe { &*this_arg.inner }.get_sighash_all(&::bitcoin::blockdata::script::Script::from(Vec::from(funding_redeemscript.to_slice())), channel_value_satoshis);
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_sighash_all(&::bitcoin::blockdata::script::Script::from(Vec::from(funding_redeemscript.to_slice())), channel_value_satoshis);
        crate::c_types::ThirtyTwoBytes { data: ret.as_ref().clone() }
 }
 
@@ -1274,7 +1322,7 @@ pub extern "C" fn BuiltCommitmentTransaction_get_sighash_all(this_arg: &BuiltCom
 #[must_use]
 #[no_mangle]
 pub extern "C" fn BuiltCommitmentTransaction_sign(this_arg: &BuiltCommitmentTransaction, funding_key: *const [u8; 32], mut funding_redeemscript: crate::c_types::u8slice, mut channel_value_satoshis: u64) -> crate::c_types::Signature {
-       let mut ret = unsafe { &*this_arg.inner }.sign(&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *funding_key}[..]).unwrap(), &::bitcoin::blockdata::script::Script::from(Vec::from(funding_redeemscript.to_slice())), channel_value_satoshis, secp256k1::SECP256K1);
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.sign(&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *funding_key}[..]).unwrap(), &::bitcoin::blockdata::script::Script::from(Vec::from(funding_redeemscript.to_slice())), channel_value_satoshis, secp256k1::SECP256K1);
        crate::c_types::Signature::from_rust(&ret)
 }
 
@@ -1306,7 +1354,7 @@ pub struct CommitmentTransaction {
 impl Drop for CommitmentTransaction {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeCommitmentTransaction>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -1319,11 +1367,17 @@ extern "C" fn CommitmentTransaction_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeCommitmentTransaction); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl CommitmentTransaction {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeCommitmentTransaction {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeCommitmentTransaction {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeCommitmentTransaction {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -1332,7 +1386,7 @@ impl Clone for CommitmentTransaction {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeCommitmentTransaction>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -1350,7 +1404,7 @@ pub extern "C" fn CommitmentTransaction_clone(orig: &CommitmentTransaction) -> C
 #[no_mangle]
 /// Serialize the CommitmentTransaction object into a byte array which can be read by CommitmentTransaction_read
 pub extern "C" fn CommitmentTransaction_write(obj: &CommitmentTransaction) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }
 #[no_mangle]
 pub(crate) extern "C" fn CommitmentTransaction_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
@@ -1360,14 +1414,14 @@ pub(crate) extern "C" fn CommitmentTransaction_write_void(obj: *const c_void) ->
 /// Read a CommitmentTransaction from a byte array, created by CommitmentTransaction_write
 pub extern "C" fn CommitmentTransaction_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_CommitmentTransactionDecodeErrorZ {
        let res = crate::c_types::deserialize_obj(ser);
-       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::CommitmentTransaction { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::CommitmentTransaction { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_res
 }
 /// The backwards-counting commitment number
 #[must_use]
 #[no_mangle]
 pub extern "C" fn CommitmentTransaction_commitment_number(this_arg: &CommitmentTransaction) -> u64 {
-       let mut ret = unsafe { &*this_arg.inner }.commitment_number();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.commitment_number();
        ret
 }
 
@@ -1375,7 +1429,7 @@ pub extern "C" fn CommitmentTransaction_commitment_number(this_arg: &CommitmentT
 #[must_use]
 #[no_mangle]
 pub extern "C" fn CommitmentTransaction_to_broadcaster_value_sat(this_arg: &CommitmentTransaction) -> u64 {
-       let mut ret = unsafe { &*this_arg.inner }.to_broadcaster_value_sat();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.to_broadcaster_value_sat();
        ret
 }
 
@@ -1383,7 +1437,7 @@ pub extern "C" fn CommitmentTransaction_to_broadcaster_value_sat(this_arg: &Comm
 #[must_use]
 #[no_mangle]
 pub extern "C" fn CommitmentTransaction_to_countersignatory_value_sat(this_arg: &CommitmentTransaction) -> u64 {
-       let mut ret = unsafe { &*this_arg.inner }.to_countersignatory_value_sat();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.to_countersignatory_value_sat();
        ret
 }
 
@@ -1391,7 +1445,7 @@ pub extern "C" fn CommitmentTransaction_to_countersignatory_value_sat(this_arg:
 #[must_use]
 #[no_mangle]
 pub extern "C" fn CommitmentTransaction_feerate_per_kw(this_arg: &CommitmentTransaction) -> u32 {
-       let mut ret = unsafe { &*this_arg.inner }.feerate_per_kw();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.feerate_per_kw();
        ret
 }
 
@@ -1404,8 +1458,8 @@ pub extern "C" fn CommitmentTransaction_feerate_per_kw(this_arg: &CommitmentTran
 #[must_use]
 #[no_mangle]
 pub extern "C" fn CommitmentTransaction_trust(this_arg: &CommitmentTransaction) -> crate::lightning::ln::chan_utils::TrustedCommitmentTransaction {
-       let mut ret = unsafe { &*this_arg.inner }.trust();
-       crate::lightning::ln::chan_utils::TrustedCommitmentTransaction { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.trust();
+       crate::lightning::ln::chan_utils::TrustedCommitmentTransaction { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 /// Verify our pre-built transaction and derived transaction creation public keys.
@@ -1417,8 +1471,8 @@ pub extern "C" fn CommitmentTransaction_trust(this_arg: &CommitmentTransaction)
 #[must_use]
 #[no_mangle]
 pub extern "C" fn CommitmentTransaction_verify(this_arg: &CommitmentTransaction, channel_parameters: &crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters, broadcaster_keys: &crate::lightning::ln::chan_utils::ChannelPublicKeys, countersignatory_keys: &crate::lightning::ln::chan_utils::ChannelPublicKeys) -> crate::c_types::derived::CResult_TrustedCommitmentTransactionNoneZ {
-       let mut ret = unsafe { &*this_arg.inner }.verify(unsafe { &*channel_parameters.inner }, unsafe { &*broadcaster_keys.inner }, unsafe { &*countersignatory_keys.inner }, secp256k1::SECP256K1);
-       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TrustedCommitmentTransaction { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.verify(channel_parameters.get_native_ref(), broadcaster_keys.get_native_ref(), countersignatory_keys.get_native_ref(), secp256k1::SECP256K1);
+       let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TrustedCommitmentTransaction { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
        local_ret
 }
 
@@ -1450,7 +1504,7 @@ pub struct TrustedCommitmentTransaction {
 impl Drop for TrustedCommitmentTransaction {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeTrustedCommitmentTransaction>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -1463,11 +1517,17 @@ extern "C" fn TrustedCommitmentTransaction_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeTrustedCommitmentTransaction); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl TrustedCommitmentTransaction {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeTrustedCommitmentTransaction {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeTrustedCommitmentTransaction {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeTrustedCommitmentTransaction {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -1476,7 +1536,7 @@ impl TrustedCommitmentTransaction {
 #[must_use]
 #[no_mangle]
 pub extern "C" fn TrustedCommitmentTransaction_txid(this_arg: &TrustedCommitmentTransaction) -> crate::c_types::ThirtyTwoBytes {
-       let mut ret = unsafe { &*this_arg.inner }.txid();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.txid();
        crate::c_types::ThirtyTwoBytes { data: ret.into_inner() }
 }
 
@@ -1484,16 +1544,16 @@ pub extern "C" fn TrustedCommitmentTransaction_txid(this_arg: &TrustedCommitment
 #[must_use]
 #[no_mangle]
 pub extern "C" fn TrustedCommitmentTransaction_built_transaction(this_arg: &TrustedCommitmentTransaction) -> crate::lightning::ln::chan_utils::BuiltCommitmentTransaction {
-       let mut ret = unsafe { &*this_arg.inner }.built_transaction();
-       crate::lightning::ln::chan_utils::BuiltCommitmentTransaction { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.built_transaction();
+       crate::lightning::ln::chan_utils::BuiltCommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false }
 }
 
 /// The pre-calculated transaction creation public keys.
 #[must_use]
 #[no_mangle]
 pub extern "C" fn TrustedCommitmentTransaction_keys(this_arg: &TrustedCommitmentTransaction) -> crate::lightning::ln::chan_utils::TxCreationKeys {
-       let mut ret = unsafe { &*this_arg.inner }.keys();
-       crate::lightning::ln::chan_utils::TxCreationKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.keys();
+       crate::lightning::ln::chan_utils::TxCreationKeys { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false }
 }
 
 /// Get a signature for each HTLC which was included in the commitment transaction (ie for
@@ -1503,7 +1563,7 @@ pub extern "C" fn TrustedCommitmentTransaction_keys(this_arg: &TrustedCommitment
 #[must_use]
 #[no_mangle]
 pub extern "C" fn TrustedCommitmentTransaction_get_htlc_sigs(this_arg: &TrustedCommitmentTransaction, htlc_base_key: *const [u8; 32], channel_parameters: &crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters) -> crate::c_types::derived::CResult_CVec_SignatureZNoneZ {
-       let mut ret = unsafe { &*this_arg.inner }.get_htlc_sigs(&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *htlc_base_key}[..]).unwrap(), unsafe { &*channel_parameters.inner }, secp256k1::SECP256K1);
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_htlc_sigs(&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *htlc_base_key}[..]).unwrap(), channel_parameters.get_native_ref(), secp256k1::SECP256K1);
        let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { crate::c_types::Signature::from_rust(&item) }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
        local_ret
 }
index 0f5d3cc3ac2a7dc484385eaf85a1d483cf9a3fbe..8982a2ba1e663797c66700d8c9ef5eddc0773399 100644 (file)
@@ -80,7 +80,7 @@ pub struct ChannelManager {
 impl Drop for ChannelManager {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeChannelManager>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -93,11 +93,17 @@ extern "C" fn ChannelManager_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelManager); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelManager {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeChannelManager {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelManager {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeChannelManager {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -129,7 +135,7 @@ pub struct ChainParameters {
 impl Drop for ChainParameters {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeChainParameters>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -142,11 +148,17 @@ extern "C" fn ChainParameters_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChainParameters); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChainParameters {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeChainParameters {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChainParameters {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeChainParameters {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -154,43 +166,43 @@ impl ChainParameters {
 /// The network for determining the `chain_hash` in Lightning messages.
 #[no_mangle]
 pub extern "C" fn ChainParameters_get_network(this_ptr: &ChainParameters) -> crate::bitcoin::network::Network {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.network;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().network;
        crate::bitcoin::network::Network::from_bitcoin(inner_val)
 }
 /// The network for determining the `chain_hash` in Lightning messages.
 #[no_mangle]
 pub extern "C" fn ChainParameters_set_network(this_ptr: &mut ChainParameters, mut val: crate::bitcoin::network::Network) {
-       unsafe { &mut *this_ptr.inner }.network = val.into_bitcoin();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.network = val.into_bitcoin();
 }
 /// The hash and height of the latest block successfully connected.
 ///
 /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
 #[no_mangle]
 pub extern "C" fn ChainParameters_get_best_block(this_ptr: &ChainParameters) -> crate::lightning::chain::BestBlock {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.best_block;
-       crate::lightning::chain::BestBlock { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false }
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().best_block;
+       crate::lightning::chain::BestBlock { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false }
 }
 /// The hash and height of the latest block successfully connected.
 ///
 /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
 #[no_mangle]
 pub extern "C" fn ChainParameters_set_best_block(this_ptr: &mut ChainParameters, mut val: crate::lightning::chain::BestBlock) {
-       unsafe { &mut *this_ptr.inner }.best_block = *unsafe { Box::from_raw(val.take_inner()) };
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.best_block = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// Constructs a new ChainParameters given each field
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChainParameters_new(mut network_arg: crate::bitcoin::network::Network, mut best_block_arg: crate::lightning::chain::BestBlock) -> ChainParameters {
-       ChainParameters { inner: Box::into_raw(Box::new(nativeChainParameters {
+       ChainParameters { inner: ObjOps::heap_alloc(nativeChainParameters {
                network: network_arg.into_bitcoin(),
                best_block: *unsafe { Box::from_raw(best_block_arg.take_inner()) },
-       })), is_owned: true }
+       }), is_owned: true }
 }
 impl Clone for ChainParameters {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeChainParameters>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -253,7 +265,7 @@ pub struct ChannelCounterparty {
 impl Drop for ChannelCounterparty {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeChannelCounterparty>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -266,11 +278,17 @@ extern "C" fn ChannelCounterparty_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelCounterparty); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelCounterparty {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeChannelCounterparty {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelCounterparty {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeChannelCounterparty {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -278,28 +296,28 @@ impl ChannelCounterparty {
 /// The node_id of our counterparty
 #[no_mangle]
 pub extern "C" fn ChannelCounterparty_get_node_id(this_ptr: &ChannelCounterparty) -> crate::c_types::PublicKey {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.node_id;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().node_id;
        crate::c_types::PublicKey::from_rust(&inner_val)
 }
 /// The node_id of our counterparty
 #[no_mangle]
 pub extern "C" fn ChannelCounterparty_set_node_id(this_ptr: &mut ChannelCounterparty, mut val: crate::c_types::PublicKey) {
-       unsafe { &mut *this_ptr.inner }.node_id = val.into_rust();
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_id = val.into_rust();
 }
 /// The Features the channel counterparty provided upon last connection.
 /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
 /// many routing-relevant features are present in the init context.
 #[no_mangle]
 pub extern "C" fn ChannelCounterparty_get_features(this_ptr: &ChannelCounterparty) -> crate::lightning::ln::features::InitFeatures {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.features;
-       crate::lightning::ln::features::InitFeatures { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false }
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().features;
+       crate::lightning::ln::features::InitFeatures { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false }
 }
 /// The Features the channel counterparty provided upon last connection.
 /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
 /// many routing-relevant features are present in the init context.
 #[no_mangle]
 pub extern "C" fn ChannelCounterparty_set_features(this_ptr: &mut ChannelCounterparty, mut val: crate::lightning::ln::features::InitFeatures) {
-       unsafe { &mut *this_ptr.inner }.features = *unsafe { Box::from_raw(val.take_inner()) };
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.features = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// The value, in satoshis, that must always be held in the channel for our counterparty. This
 /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
@@ -310,7 +328,7 @@ pub extern "C" fn ChannelCounterparty_set_features(this_ptr: &mut ChannelCounter
 /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
 #[no_mangle]
 pub extern "C" fn ChannelCounterparty_get_unspendable_punishment_reserve(this_ptr: &ChannelCounterparty) -> u64 {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.unspendable_punishment_reserve;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().unspendable_punishment_reserve;
        *inner_val
 }
 /// The value, in satoshis, that must always be held in the channel for our counterparty. This
@@ -322,13 +340,13 @@ pub extern "C" fn ChannelCounterparty_get_unspendable_punishment_reserve(this_pt
 /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
 #[no_mangle]
 pub extern "C" fn ChannelCounterparty_set_unspendable_punishment_reserve(this_ptr: &mut ChannelCounterparty, mut val: u64) {
-       unsafe { &mut *this_ptr.inner }.unspendable_punishment_reserve = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.unspendable_punishment_reserve = val;
 }
 impl Clone for ChannelCounterparty {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeChannelCounterparty>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -366,7 +384,7 @@ pub struct ChannelDetails {
 impl Drop for ChannelDetails {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeChannelDetails>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -379,11 +397,17 @@ extern "C" fn ChannelDetails_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelDetails); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelDetails {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeChannelDetails {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelDetails {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeChannelDetails {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -394,7 +418,7 @@ impl ChannelDetails {
 /// lifetime of the channel.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_get_channel_id(this_ptr: &ChannelDetails) -> *const [u8; 32] {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id;
        inner_val
 }
 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
@@ -403,18 +427,18 @@ pub extern "C" fn ChannelDetails_get_channel_id(this_ptr: &ChannelDetails) -> *c
 /// lifetime of the channel.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_set_channel_id(this_ptr: &mut ChannelDetails, mut val: crate::c_types::ThirtyTwoBytes) {
-       unsafe { &mut *this_ptr.inner }.channel_id = val.data;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_id = val.data;
 }
 /// Parameters which apply to our counterparty. See individual fields for more information.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_get_counterparty(this_ptr: &ChannelDetails) -> crate::lightning::ln::channelmanager::ChannelCounterparty {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.counterparty;
-       crate::lightning::ln::channelmanager::ChannelCounterparty { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false }
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().counterparty;
+       crate::lightning::ln::channelmanager::ChannelCounterparty { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false }
 }
 /// Parameters which apply to our counterparty. See individual fields for more information.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_set_counterparty(this_ptr: &mut ChannelDetails, mut val: crate::lightning::ln::channelmanager::ChannelCounterparty) {
-       unsafe { &mut *this_ptr.inner }.counterparty = *unsafe { Box::from_raw(val.take_inner()) };
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.counterparty = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// The Channel's funding transaction output, if we've negotiated the funding transaction with
 /// our counterparty already.
@@ -425,8 +449,8 @@ pub extern "C" fn ChannelDetails_set_counterparty(this_ptr: &mut ChannelDetails,
 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
 #[no_mangle]
 pub extern "C" fn ChannelDetails_get_funding_txo(this_ptr: &ChannelDetails) -> crate::lightning::chain::transaction::OutPoint {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_txo;
-       let mut local_inner_val = crate::lightning::chain::transaction::OutPoint { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else {  { (inner_val.as_ref().unwrap()) } } as *const _) as *mut _ }, is_owned: false };
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().funding_txo;
+       let mut local_inner_val = crate::lightning::chain::transaction::OutPoint { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const _) as *mut _ }, is_owned: false };
        local_inner_val
 }
 /// The Channel's funding transaction output, if we've negotiated the funding transaction with
@@ -439,13 +463,13 @@ pub extern "C" fn ChannelDetails_get_funding_txo(this_ptr: &ChannelDetails) -> c
 #[no_mangle]
 pub extern "C" fn ChannelDetails_set_funding_txo(this_ptr: &mut ChannelDetails, mut val: crate::lightning::chain::transaction::OutPoint) {
        let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
-       unsafe { &mut *this_ptr.inner }.funding_txo = local_val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.funding_txo = local_val;
 }
 /// The position of the funding transaction in the chain. None if the funding transaction has
 /// not yet been confirmed and the channel fully opened.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_get_short_channel_id(this_ptr: &ChannelDetails) -> crate::c_types::derived::COption_u64Z {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.short_channel_id;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().short_channel_id;
        let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u64Z::None } else {  { crate::c_types::derived::COption_u64Z::Some(inner_val.unwrap()) } };
        local_inner_val
 }
@@ -454,18 +478,18 @@ pub extern "C" fn ChannelDetails_get_short_channel_id(this_ptr: &ChannelDetails)
 #[no_mangle]
 pub extern "C" fn ChannelDetails_set_short_channel_id(this_ptr: &mut ChannelDetails, mut val: crate::c_types::derived::COption_u64Z) {
        let mut local_val = if val.is_some() { Some( { val.take() }) } else { None };
-       unsafe { &mut *this_ptr.inner }.short_channel_id = local_val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.short_channel_id = local_val;
 }
 /// The value, in satoshis, of this channel as appears in the funding output
 #[no_mangle]
 pub extern "C" fn ChannelDetails_get_channel_value_satoshis(this_ptr: &ChannelDetails) -> u64 {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_value_satoshis;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_value_satoshis;
        *inner_val
 }
 /// The value, in satoshis, of this channel as appears in the funding output
 #[no_mangle]
 pub extern "C" fn ChannelDetails_set_channel_value_satoshis(this_ptr: &mut ChannelDetails, mut val: u64) {
-       unsafe { &mut *this_ptr.inner }.channel_value_satoshis = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_value_satoshis = val;
 }
 /// The value, in satoshis, that must always be held in the channel for us. This value ensures
 /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
@@ -478,7 +502,7 @@ pub extern "C" fn ChannelDetails_set_channel_value_satoshis(this_ptr: &mut Chann
 /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
 #[no_mangle]
 pub extern "C" fn ChannelDetails_get_unspendable_punishment_reserve(this_ptr: &ChannelDetails) -> crate::c_types::derived::COption_u64Z {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.unspendable_punishment_reserve;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().unspendable_punishment_reserve;
        let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u64Z::None } else {  { crate::c_types::derived::COption_u64Z::Some(inner_val.unwrap()) } };
        local_inner_val
 }
@@ -494,18 +518,18 @@ pub extern "C" fn ChannelDetails_get_unspendable_punishment_reserve(this_ptr: &C
 #[no_mangle]
 pub extern "C" fn ChannelDetails_set_unspendable_punishment_reserve(this_ptr: &mut ChannelDetails, mut val: crate::c_types::derived::COption_u64Z) {
        let mut local_val = if val.is_some() { Some( { val.take() }) } else { None };
-       unsafe { &mut *this_ptr.inner }.unspendable_punishment_reserve = local_val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.unspendable_punishment_reserve = local_val;
 }
 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_get_user_id(this_ptr: &ChannelDetails) -> u64 {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.user_id;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().user_id;
        *inner_val
 }
 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_set_user_id(this_ptr: &mut ChannelDetails, mut val: u64) {
-       unsafe { &mut *this_ptr.inner }.user_id = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.user_id = val;
 }
 /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
 /// any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
@@ -517,7 +541,7 @@ pub extern "C" fn ChannelDetails_set_user_id(this_ptr: &mut ChannelDetails, mut
 /// should be able to spend nearly this amount.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_get_outbound_capacity_msat(this_ptr: &ChannelDetails) -> u64 {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.outbound_capacity_msat;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().outbound_capacity_msat;
        *inner_val
 }
 /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
@@ -530,7 +554,7 @@ pub extern "C" fn ChannelDetails_get_outbound_capacity_msat(this_ptr: &ChannelDe
 /// should be able to spend nearly this amount.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_set_outbound_capacity_msat(this_ptr: &mut ChannelDetails, mut val: u64) {
-       unsafe { &mut *this_ptr.inner }.outbound_capacity_msat = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outbound_capacity_msat = val;
 }
 /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
 /// include any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
@@ -543,7 +567,7 @@ pub extern "C" fn ChannelDetails_set_outbound_capacity_msat(this_ptr: &mut Chann
 /// However, our counterparty should be able to spend nearly this amount.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_get_inbound_capacity_msat(this_ptr: &ChannelDetails) -> u64 {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.inbound_capacity_msat;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().inbound_capacity_msat;
        *inner_val
 }
 /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
@@ -557,7 +581,7 @@ pub extern "C" fn ChannelDetails_get_inbound_capacity_msat(this_ptr: &ChannelDet
 /// However, our counterparty should be able to spend nearly this amount.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_set_inbound_capacity_msat(this_ptr: &mut ChannelDetails, mut val: u64) {
-       unsafe { &mut *this_ptr.inner }.inbound_capacity_msat = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.inbound_capacity_msat = val;
 }
 /// The number of required confirmations on the funding transaction before the funding will be
 /// considered \"locked\". This number is selected by the channel fundee (i.e. us if
@@ -572,7 +596,7 @@ pub extern "C" fn ChannelDetails_set_inbound_capacity_msat(this_ptr: &mut Channe
 /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
 #[no_mangle]
 pub extern "C" fn ChannelDetails_get_confirmations_required(this_ptr: &ChannelDetails) -> crate::c_types::derived::COption_u32Z {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.confirmations_required;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().confirmations_required;
        let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u32Z::None } else {  { crate::c_types::derived::COption_u32Z::Some(inner_val.unwrap()) } };
        local_inner_val
 }
@@ -590,7 +614,7 @@ pub extern "C" fn ChannelDetails_get_confirmations_required(this_ptr: &ChannelDe
 #[no_mangle]
 pub extern "C" fn ChannelDetails_set_confirmations_required(this_ptr: &mut ChannelDetails, mut val: crate::c_types::derived::COption_u32Z) {
        let mut local_val = if val.is_some() { Some( { val.take() }) } else { None };
-       unsafe { &mut *this_ptr.inner }.confirmations_required = local_val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.confirmations_required = local_val;
 }
 /// The number of blocks (after our commitment transaction confirms) that we will need to wait
 /// until we can claim our funds after we force-close the channel. During this time our
@@ -601,7 +625,7 @@ pub extern "C" fn ChannelDetails_set_confirmations_required(this_ptr: &mut Chann
 /// This value will be `None` for outbound channels until the counterparty accepts the channel.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_get_force_close_spend_delay(this_ptr: &ChannelDetails) -> crate::c_types::derived::COption_u16Z {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.force_close_spend_delay;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().force_close_spend_delay;
        let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u16Z::None } else {  { crate::c_types::derived::COption_u16Z::Some(inner_val.unwrap()) } };
        local_inner_val
 }
@@ -615,18 +639,18 @@ pub extern "C" fn ChannelDetails_get_force_close_spend_delay(this_ptr: &ChannelD
 #[no_mangle]
 pub extern "C" fn ChannelDetails_set_force_close_spend_delay(this_ptr: &mut ChannelDetails, mut val: crate::c_types::derived::COption_u16Z) {
        let mut local_val = if val.is_some() { Some( { val.take() }) } else { None };
-       unsafe { &mut *this_ptr.inner }.force_close_spend_delay = local_val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.force_close_spend_delay = local_val;
 }
 /// True if the channel was initiated (and thus funded) by us.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_get_is_outbound(this_ptr: &ChannelDetails) -> bool {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.is_outbound;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().is_outbound;
        *inner_val
 }
 /// True if the channel was initiated (and thus funded) by us.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_set_is_outbound(this_ptr: &mut ChannelDetails, mut val: bool) {
-       unsafe { &mut *this_ptr.inner }.is_outbound = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.is_outbound = val;
 }
 /// True if the channel is confirmed, funding_locked messages have been exchanged, and the
 /// channel is not currently being shut down. `funding_locked` message exchange implies the
@@ -637,7 +661,7 @@ pub extern "C" fn ChannelDetails_set_is_outbound(this_ptr: &mut ChannelDetails,
 /// [`confirmations_required`]: ChannelDetails::confirmations_required
 #[no_mangle]
 pub extern "C" fn ChannelDetails_get_is_funding_locked(this_ptr: &ChannelDetails) -> bool {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.is_funding_locked;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().is_funding_locked;
        *inner_val
 }
 /// True if the channel is confirmed, funding_locked messages have been exchanged, and the
@@ -649,7 +673,7 @@ pub extern "C" fn ChannelDetails_get_is_funding_locked(this_ptr: &ChannelDetails
 /// [`confirmations_required`]: ChannelDetails::confirmations_required
 #[no_mangle]
 pub extern "C" fn ChannelDetails_set_is_funding_locked(this_ptr: &mut ChannelDetails, mut val: bool) {
-       unsafe { &mut *this_ptr.inner }.is_funding_locked = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.is_funding_locked = val;
 }
 /// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b)
 /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
@@ -657,7 +681,7 @@ pub extern "C" fn ChannelDetails_set_is_funding_locked(this_ptr: &mut ChannelDet
 /// This is a strict superset of `is_funding_locked`.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_get_is_usable(this_ptr: &ChannelDetails) -> bool {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.is_usable;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().is_usable;
        *inner_val
 }
 /// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b)
@@ -666,18 +690,18 @@ pub extern "C" fn ChannelDetails_get_is_usable(this_ptr: &ChannelDetails) -> boo
 /// This is a strict superset of `is_funding_locked`.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_set_is_usable(this_ptr: &mut ChannelDetails, mut val: bool) {
-       unsafe { &mut *this_ptr.inner }.is_usable = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.is_usable = val;
 }
 /// True if this channel is (or will be) publicly-announced.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_get_is_public(this_ptr: &ChannelDetails) -> bool {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.is_public;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().is_public;
        *inner_val
 }
 /// True if this channel is (or will be) publicly-announced.
 #[no_mangle]
 pub extern "C" fn ChannelDetails_set_is_public(this_ptr: &mut ChannelDetails, mut val: bool) {
-       unsafe { &mut *this_ptr.inner }.is_public = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.is_public = val;
 }
 /// Constructs a new ChannelDetails given each field
 #[must_use]
@@ -688,7 +712,7 @@ pub extern "C" fn ChannelDetails_new(mut channel_id_arg: crate::c_types::ThirtyT
        let mut local_unspendable_punishment_reserve_arg = if unspendable_punishment_reserve_arg.is_some() { Some( { unspendable_punishment_reserve_arg.take() }) } else { None };
        let mut local_confirmations_required_arg = if confirmations_required_arg.is_some() { Some( { confirmations_required_arg.take() }) } else { None };
        let mut local_force_close_spend_delay_arg = if force_close_spend_delay_arg.is_some() { Some( { force_close_spend_delay_arg.take() }) } else { None };
-       ChannelDetails { inner: Box::into_raw(Box::new(nativeChannelDetails {
+       ChannelDetails { inner: ObjOps::heap_alloc(nativeChannelDetails {
                channel_id: channel_id_arg.data,
                counterparty: *unsafe { Box::from_raw(counterparty_arg.take_inner()) },
                funding_txo: local_funding_txo_arg,
@@ -704,13 +728,13 @@ pub extern "C" fn ChannelDetails_new(mut channel_id_arg: crate::c_types::ThirtyT
                is_funding_locked: is_funding_locked_arg,
                is_usable: is_usable_arg,
                is_public: is_public_arg,
-       })), is_owned: true }
+       }), is_owned: true }
 }
 impl Clone for ChannelDetails {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeChannelDetails>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -929,15 +953,15 @@ pub extern "C" fn PaymentSendFailure_partial_failure(a: crate::c_types::derived:
 #[no_mangle]
 pub extern "C" fn ChannelManager_new(mut fee_est: crate::lightning::chain::chaininterface::FeeEstimator, mut chain_monitor: crate::lightning::chain::Watch, mut tx_broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut logger: crate::lightning::util::logger::Logger, mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface, mut config: crate::lightning::util::config::UserConfig, mut params: crate::lightning::ln::channelmanager::ChainParameters) -> ChannelManager {
        let mut ret = lightning::ln::channelmanager::ChannelManager::new(fee_est, chain_monitor, tx_broadcaster, logger, keys_manager, *unsafe { Box::from_raw(config.take_inner()) }, *unsafe { Box::from_raw(params.take_inner()) });
-       ChannelManager { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       ChannelManager { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 /// Gets the current configuration applied to all new channels,  as
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManager_get_current_default_configuration(this_arg: &ChannelManager) -> crate::lightning::util::config::UserConfig {
-       let mut ret = unsafe { &*this_arg.inner }.get_current_default_configuration();
-       crate::lightning::util::config::UserConfig { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_current_default_configuration();
+       crate::lightning::util::config::UserConfig { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false }
 }
 
 /// Creates a new outbound channel to the given remote node and with the given value.
@@ -963,7 +987,7 @@ pub extern "C" fn ChannelManager_get_current_default_configuration(this_arg: &Ch
 #[no_mangle]
 pub extern "C" fn ChannelManager_create_channel(this_arg: &ChannelManager, mut their_network_key: crate::c_types::PublicKey, mut channel_value_satoshis: u64, mut push_msat: u64, mut user_id: u64, mut override_config: crate::lightning::util::config::UserConfig) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
        let mut local_override_config = if override_config.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(override_config.take_inner()) } }) };
-       let mut ret = unsafe { &*this_arg.inner }.create_channel(their_network_key.into_rust(), channel_value_satoshis, push_msat, user_id, local_override_config);
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.create_channel(their_network_key.into_rust(), channel_value_satoshis, push_msat, user_id, local_override_config);
        let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
        local_ret
 }
@@ -973,8 +997,8 @@ pub extern "C" fn ChannelManager_create_channel(this_arg: &ChannelManager, mut t
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManager_list_channels(this_arg: &ChannelManager) -> crate::c_types::derived::CVec_ChannelDetailsZ {
-       let mut ret = unsafe { &*this_arg.inner }.list_channels();
-       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::channelmanager::ChannelDetails { inner: Box::into_raw(Box::new(item)), is_owned: true } }); };
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.list_channels();
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::channelmanager::ChannelDetails { inner: ObjOps::heap_alloc(item), is_owned: true } }); };
        local_ret.into()
 }
 
@@ -987,8 +1011,8 @@ pub extern "C" fn ChannelManager_list_channels(this_arg: &ChannelManager) -> cra
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManager_list_usable_channels(this_arg: &ChannelManager) -> crate::c_types::derived::CVec_ChannelDetailsZ {
-       let mut ret = unsafe { &*this_arg.inner }.list_usable_channels();
-       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::channelmanager::ChannelDetails { inner: Box::into_raw(Box::new(item)), is_owned: true } }); };
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.list_usable_channels();
+       let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::channelmanager::ChannelDetails { inner: ObjOps::heap_alloc(item), is_owned: true } }); };
        local_ret.into()
 }
 
@@ -1012,7 +1036,7 @@ pub extern "C" fn ChannelManager_list_usable_channels(this_arg: &ChannelManager)
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManager_close_channel(this_arg: &ChannelManager, channel_id: *const [u8; 32]) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
-       let mut ret = unsafe { &*this_arg.inner }.close_channel(unsafe { &*channel_id});
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.close_channel(unsafe { &*channel_id});
        let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
        local_ret
 }
@@ -1039,7 +1063,7 @@ pub extern "C" fn ChannelManager_close_channel(this_arg: &ChannelManager, channe
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManager_close_channel_with_target_feerate(this_arg: &ChannelManager, channel_id: *const [u8; 32], mut target_feerate_sats_per_1000_weight: u32) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
-       let mut ret = unsafe { &*this_arg.inner }.close_channel_with_target_feerate(unsafe { &*channel_id}, target_feerate_sats_per_1000_weight);
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.close_channel_with_target_feerate(unsafe { &*channel_id}, target_feerate_sats_per_1000_weight);
        let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
        local_ret
 }
@@ -1049,7 +1073,7 @@ pub extern "C" fn ChannelManager_close_channel_with_target_feerate(this_arg: &Ch
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManager_force_close_channel(this_arg: &ChannelManager, channel_id: *const [u8; 32]) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
-       let mut ret = unsafe { &*this_arg.inner }.force_close_channel(unsafe { &*channel_id});
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.force_close_channel(unsafe { &*channel_id});
        let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
        local_ret
 }
@@ -1058,7 +1082,7 @@ pub extern "C" fn ChannelManager_force_close_channel(this_arg: &ChannelManager,
 /// for each to the chain and rejecting new HTLCs on each.
 #[no_mangle]
 pub extern "C" fn ChannelManager_force_close_all_channels(this_arg: &ChannelManager) {
-       unsafe { &*this_arg.inner }.force_close_all_channels()
+       unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.force_close_all_channels()
 }
 
 /// Sends a payment along a given route.
@@ -1106,7 +1130,7 @@ pub extern "C" fn ChannelManager_force_close_all_channels(this_arg: &ChannelMana
 #[no_mangle]
 pub extern "C" fn ChannelManager_send_payment(this_arg: &ChannelManager, route: &crate::lightning::routing::router::Route, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut payment_secret: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ {
        let mut local_payment_secret = if payment_secret.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentSecret(payment_secret.data) }) };
-       let mut ret = unsafe { &*this_arg.inner }.send_payment(unsafe { &*route.inner }, ::lightning::ln::PaymentHash(payment_hash.data), &local_payment_secret);
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_payment(route.get_native_ref(), ::lightning::ln::PaymentHash(payment_hash.data), &local_payment_secret);
        let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(e) }).into() };
        local_ret
 }
@@ -1131,7 +1155,7 @@ pub extern "C" fn ChannelManager_send_payment(this_arg: &ChannelManager, route:
 #[no_mangle]
 pub extern "C" fn ChannelManager_send_spontaneous_payment(this_arg: &ChannelManager, route: &crate::lightning::routing::router::Route, mut payment_preimage: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_PaymentHashPaymentSendFailureZ {
        let mut local_payment_preimage = if payment_preimage.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentPreimage(payment_preimage.data) }) };
-       let mut ret = unsafe { &*this_arg.inner }.send_spontaneous_payment(unsafe { &*route.inner }, local_payment_preimage);
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_spontaneous_payment(route.get_native_ref(), local_payment_preimage);
        let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(e) }).into() };
        local_ret
 }
@@ -1159,7 +1183,7 @@ pub extern "C" fn ChannelManager_send_spontaneous_payment(this_arg: &ChannelMana
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManager_funding_transaction_generated(this_arg: &ChannelManager, temporary_channel_id: *const [u8; 32], mut funding_transaction: crate::c_types::Transaction) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
-       let mut ret = unsafe { &*this_arg.inner }.funding_transaction_generated(unsafe { &*temporary_channel_id}, funding_transaction.into_bitcoin());
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.funding_transaction_generated(unsafe { &*temporary_channel_id}, funding_transaction.into_bitcoin());
        let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
        local_ret
 }
@@ -1185,7 +1209,7 @@ pub extern "C" fn ChannelManager_funding_transaction_generated(this_arg: &Channe
 #[no_mangle]
 pub extern "C" fn ChannelManager_broadcast_node_announcement(this_arg: &ChannelManager, mut rgb: crate::c_types::ThreeBytes, mut alias: crate::c_types::ThirtyTwoBytes, mut addresses: crate::c_types::derived::CVec_NetAddressZ) {
        let mut local_addresses = Vec::new(); for mut item in addresses.into_rust().drain(..) { local_addresses.push( { item.into_native() }); };
-       unsafe { &*this_arg.inner }.broadcast_node_announcement(rgb.data, alias.data, local_addresses)
+       unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.broadcast_node_announcement(rgb.data, alias.data, local_addresses)
 }
 
 /// Processes HTLCs which are pending waiting on random forward delay.
@@ -1194,7 +1218,7 @@ pub extern "C" fn ChannelManager_broadcast_node_announcement(this_arg: &ChannelM
 /// Will likely generate further events.
 #[no_mangle]
 pub extern "C" fn ChannelManager_process_pending_htlc_forwards(this_arg: &ChannelManager) {
-       unsafe { &*this_arg.inner }.process_pending_htlc_forwards()
+       unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.process_pending_htlc_forwards()
 }
 
 /// Performs actions which should happen on startup and roughly once per minute thereafter.
@@ -1209,7 +1233,7 @@ pub extern "C" fn ChannelManager_process_pending_htlc_forwards(this_arg: &Channe
 /// estimate fetches.
 #[no_mangle]
 pub extern "C" fn ChannelManager_timer_tick_occurred(this_arg: &ChannelManager) {
-       unsafe { &*this_arg.inner }.timer_tick_occurred()
+       unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.timer_tick_occurred()
 }
 
 /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
@@ -1220,7 +1244,7 @@ pub extern "C" fn ChannelManager_timer_tick_occurred(this_arg: &ChannelManager)
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManager_fail_htlc_backwards(this_arg: &ChannelManager, payment_hash: *const [u8; 32]) -> bool {
-       let mut ret = unsafe { &*this_arg.inner }.fail_htlc_backwards(&::lightning::ln::PaymentHash(unsafe { *payment_hash }));
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.fail_htlc_backwards(&::lightning::ln::PaymentHash(unsafe { *payment_hash }));
        ret
 }
 
@@ -1240,7 +1264,7 @@ pub extern "C" fn ChannelManager_fail_htlc_backwards(this_arg: &ChannelManager,
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManager_claim_funds(this_arg: &ChannelManager, mut payment_preimage: crate::c_types::ThirtyTwoBytes) -> bool {
-       let mut ret = unsafe { &*this_arg.inner }.claim_funds(::lightning::ln::PaymentPreimage(payment_preimage.data));
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.claim_funds(::lightning::ln::PaymentPreimage(payment_preimage.data));
        ret
 }
 
@@ -1248,7 +1272,7 @@ pub extern "C" fn ChannelManager_claim_funds(this_arg: &ChannelManager, mut paym
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManager_get_our_node_id(this_arg: &ChannelManager) -> crate::c_types::PublicKey {
-       let mut ret = unsafe { &*this_arg.inner }.get_our_node_id();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_our_node_id();
        crate::c_types::PublicKey::from_rust(&ret)
 }
 
@@ -1274,7 +1298,7 @@ pub extern "C" fn ChannelManager_get_our_node_id(this_arg: &ChannelManager) -> c
 ///     completed, and once it is the latest the Channel will be re-enabled.
 #[no_mangle]
 pub extern "C" fn ChannelManager_channel_monitor_updated(this_arg: &ChannelManager, funding_txo: &crate::lightning::chain::transaction::OutPoint, mut highest_applied_update_id: u64) {
-       unsafe { &*this_arg.inner }.channel_monitor_updated(unsafe { &*funding_txo.inner }, highest_applied_update_id)
+       unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.channel_monitor_updated(funding_txo.get_native_ref(), highest_applied_update_id)
 }
 
 /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
@@ -1297,7 +1321,7 @@ pub extern "C" fn ChannelManager_channel_monitor_updated(this_arg: &ChannelManag
 #[no_mangle]
 pub extern "C" fn ChannelManager_create_inbound_payment(this_arg: &ChannelManager, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut invoice_expiry_delta_secs: u32, mut user_payment_id: u64) -> crate::c_types::derived::C2Tuple_PaymentHashPaymentSecretZ {
        let mut local_min_value_msat = if min_value_msat.is_some() { Some( { min_value_msat.take() }) } else { None };
-       let mut ret = unsafe { &*this_arg.inner }.create_inbound_payment(local_min_value_msat, invoice_expiry_delta_secs, user_payment_id);
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.create_inbound_payment(local_min_value_msat, invoice_expiry_delta_secs, user_payment_id);
        let (mut orig_ret_0, mut orig_ret_1) = ret; let mut local_ret = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0.0 }, crate::c_types::ThirtyTwoBytes { data: orig_ret_1.0 }).into();
        local_ret
 }
@@ -1351,14 +1375,14 @@ pub extern "C" fn ChannelManager_create_inbound_payment(this_arg: &ChannelManage
 #[no_mangle]
 pub extern "C" fn ChannelManager_create_inbound_payment_for_hash(this_arg: &ChannelManager, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut invoice_expiry_delta_secs: u32, mut user_payment_id: u64) -> crate::c_types::derived::CResult_PaymentSecretAPIErrorZ {
        let mut local_min_value_msat = if min_value_msat.is_some() { Some( { min_value_msat.take() }) } else { None };
-       let mut ret = unsafe { &*this_arg.inner }.create_inbound_payment_for_hash(::lightning::ln::PaymentHash(payment_hash.data), local_min_value_msat, invoice_expiry_delta_secs, user_payment_id);
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.create_inbound_payment_for_hash(::lightning::ln::PaymentHash(payment_hash.data), local_min_value_msat, invoice_expiry_delta_secs, user_payment_id);
        let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
        local_ret
 }
 
 impl From<nativeChannelManager> for crate::lightning::util::events::MessageSendEventsProvider {
        fn from(obj: nativeChannelManager) -> Self {
-               let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut rust_obj = ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true };
                let mut ret = ChannelManager_as_MessageSendEventsProvider(&rust_obj);
                // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
                rust_obj.inner = std::ptr::null_mut();
@@ -1371,7 +1395,7 @@ impl From<nativeChannelManager> for crate::lightning::util::events::MessageSendE
 #[no_mangle]
 pub extern "C" fn ChannelManager_as_MessageSendEventsProvider(this_arg: &ChannelManager) -> crate::lightning::util::events::MessageSendEventsProvider {
        crate::lightning::util::events::MessageSendEventsProvider {
-               this_arg: unsafe { (*this_arg).inner as *mut c_void },
+               this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
                free: None,
                get_and_clear_pending_msg_events: ChannelManager_MessageSendEventsProvider_get_and_clear_pending_msg_events,
        }
@@ -1386,7 +1410,7 @@ extern "C" fn ChannelManager_MessageSendEventsProvider_get_and_clear_pending_msg
 
 impl From<nativeChannelManager> for crate::lightning::util::events::EventsProvider {
        fn from(obj: nativeChannelManager) -> Self {
-               let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut rust_obj = ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true };
                let mut ret = ChannelManager_as_EventsProvider(&rust_obj);
                // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
                rust_obj.inner = std::ptr::null_mut();
@@ -1399,7 +1423,7 @@ impl From<nativeChannelManager> for crate::lightning::util::events::EventsProvid
 #[no_mangle]
 pub extern "C" fn ChannelManager_as_EventsProvider(this_arg: &ChannelManager) -> crate::lightning::util::events::EventsProvider {
        crate::lightning::util::events::EventsProvider {
-               this_arg: unsafe { (*this_arg).inner as *mut c_void },
+               this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
                free: None,
                process_pending_events: ChannelManager_EventsProvider_process_pending_events,
        }
@@ -1411,7 +1435,7 @@ extern "C" fn ChannelManager_EventsProvider_process_pending_events(this_arg: *co
 
 impl From<nativeChannelManager> for crate::lightning::chain::Listen {
        fn from(obj: nativeChannelManager) -> Self {
-               let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut rust_obj = ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true };
                let mut ret = ChannelManager_as_Listen(&rust_obj);
                // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
                rust_obj.inner = std::ptr::null_mut();
@@ -1424,7 +1448,7 @@ impl From<nativeChannelManager> for crate::lightning::chain::Listen {
 #[no_mangle]
 pub extern "C" fn ChannelManager_as_Listen(this_arg: &ChannelManager) -> crate::lightning::chain::Listen {
        crate::lightning::chain::Listen {
-               this_arg: unsafe { (*this_arg).inner as *mut c_void },
+               this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
                free: None,
                block_connected: ChannelManager_Listen_block_connected,
                block_disconnected: ChannelManager_Listen_block_disconnected,
@@ -1440,7 +1464,7 @@ extern "C" fn ChannelManager_Listen_block_disconnected(this_arg: *const c_void,
 
 impl From<nativeChannelManager> for crate::lightning::chain::Confirm {
        fn from(obj: nativeChannelManager) -> Self {
-               let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut rust_obj = ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true };
                let mut ret = ChannelManager_as_Confirm(&rust_obj);
                // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
                rust_obj.inner = std::ptr::null_mut();
@@ -1453,7 +1477,7 @@ impl From<nativeChannelManager> for crate::lightning::chain::Confirm {
 #[no_mangle]
 pub extern "C" fn ChannelManager_as_Confirm(this_arg: &ChannelManager) -> crate::lightning::chain::Confirm {
        crate::lightning::chain::Confirm {
-               this_arg: unsafe { (*this_arg).inner as *mut c_void },
+               this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
                free: None,
                transactions_confirmed: ChannelManager_Confirm_transactions_confirmed,
                transaction_unconfirmed: ChannelManager_Confirm_transaction_unconfirmed,
@@ -1487,7 +1511,7 @@ extern "C" fn ChannelManager_Confirm_transaction_unconfirmed(this_arg: *const c_
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManager_await_persistable_update_timeout(this_arg: &ChannelManager, mut max_wait: u64) -> bool {
-       let mut ret = unsafe { &*this_arg.inner }.await_persistable_update_timeout(std::time::Duration::from_secs(max_wait));
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.await_persistable_update_timeout(std::time::Duration::from_secs(max_wait));
        ret
 }
 
@@ -1496,7 +1520,7 @@ pub extern "C" fn ChannelManager_await_persistable_update_timeout(this_arg: &Cha
 /// up.
 #[no_mangle]
 pub extern "C" fn ChannelManager_await_persistable_update(this_arg: &ChannelManager) {
-       unsafe { &*this_arg.inner }.await_persistable_update()
+       unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.await_persistable_update()
 }
 
 /// Gets the latest best block which was connected either via the [`chain::Listen`] or
@@ -1504,13 +1528,13 @@ pub extern "C" fn ChannelManager_await_persistable_update(this_arg: &ChannelMana
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManager_current_best_block(this_arg: &ChannelManager) -> crate::lightning::chain::BestBlock {
-       let mut ret = unsafe { &*this_arg.inner }.current_best_block();
-       crate::lightning::chain::BestBlock { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.current_best_block();
+       crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 impl From<nativeChannelManager> for crate::lightning::ln::msgs::ChannelMessageHandler {
        fn from(obj: nativeChannelManager) -> Self {
-               let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
+               let mut rust_obj = ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true };
                let mut ret = ChannelManager_as_ChannelMessageHandler(&rust_obj);
                // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
                rust_obj.inner = std::ptr::null_mut();
@@ -1523,7 +1547,7 @@ impl From<nativeChannelManager> for crate::lightning::ln::msgs::ChannelMessageHa
 #[no_mangle]
 pub extern "C" fn ChannelManager_as_ChannelMessageHandler(this_arg: &ChannelManager) -> crate::lightning::ln::msgs::ChannelMessageHandler {
        crate::lightning::ln::msgs::ChannelMessageHandler {
-               this_arg: unsafe { (*this_arg).inner as *mut c_void },
+               this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
                free: None,
                handle_open_channel: ChannelManager_ChannelMessageHandler_handle_open_channel,
                handle_accept_channel: ChannelManager_ChannelMessageHandler_handle_accept_channel,
@@ -1546,7 +1570,7 @@ pub extern "C" fn ChannelManager_as_ChannelMessageHandler(this_arg: &ChannelMana
                handle_channel_update: ChannelManager_ChannelMessageHandler_handle_channel_update,
                handle_error: ChannelManager_ChannelMessageHandler_handle_error,
                MessageSendEventsProvider: crate::lightning::util::events::MessageSendEventsProvider {
-                       this_arg: unsafe { (*this_arg).inner as *mut c_void },
+                       this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
                        free: None,
                        get_and_clear_pending_msg_events: ChannelManager_MessageSendEventsProvider_get_and_clear_pending_msg_events,
                },
@@ -1554,70 +1578,70 @@ pub extern "C" fn ChannelManager_as_ChannelMessageHandler(this_arg: &ChannelMana
 }
 
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_open_channel(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, mut their_features: crate::lightning::ln::features::InitFeatures, msg: &crate::lightning::ln::msgs::OpenChannel) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_open_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_inner()) }, unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_open_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_inner()) }, msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_accept_channel(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, mut their_features: crate::lightning::ln::features::InitFeatures, msg: &crate::lightning::ln::msgs::AcceptChannel) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_accept_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_inner()) }, unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_accept_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_inner()) }, msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_created(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::FundingCreated) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_funding_created(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_funding_created(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_signed(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::FundingSigned) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_funding_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_funding_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_locked(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::FundingLocked) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_funding_locked(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_funding_locked(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_shutdown(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, their_features: &crate::lightning::ln::features::InitFeatures, msg: &crate::lightning::ln::msgs::Shutdown) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_shutdown(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*their_features.inner }, unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_shutdown(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), their_features.get_native_ref(), msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_closing_signed(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ClosingSigned) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_closing_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_closing_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_add_htlc(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateAddHTLC) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_update_add_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_update_add_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fulfill_htlc(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFulfillHTLC) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_update_fulfill_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_update_fulfill_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fail_htlc(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFailHTLC) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_update_fail_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_update_fail_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fail_malformed_htlc(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFailMalformedHTLC) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_update_fail_malformed_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_update_fail_malformed_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_commitment_signed(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::CommitmentSigned) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_commitment_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_commitment_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_revoke_and_ack(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::RevokeAndACK) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_revoke_and_ack(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_revoke_and_ack(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fee(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFee) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_update_fee(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_update_fee(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_announcement_signatures(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::AnnouncementSignatures) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_announcement_signatures(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_announcement_signatures(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_channel_update(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ChannelUpdate) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_channel_update(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_channel_update(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_channel_reestablish(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ChannelReestablish) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_channel_reestablish(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_channel_reestablish(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_peer_disconnected(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, mut no_connection_possible: bool) {
        <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), no_connection_possible)
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_peer_connected(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, init_msg: &crate::lightning::ln::msgs::Init) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::peer_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*init_msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::peer_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), init_msg.get_native_ref())
 }
 extern "C" fn ChannelManager_ChannelMessageHandler_handle_error(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ErrorMessage) {
-       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_error(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
+       <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_error(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), msg.get_native_ref())
 }
 
 #[no_mangle]
 /// Serialize the ChannelManager object into a byte array which can be read by ChannelManager_read
 pub extern "C" fn ChannelManager_write(obj: &ChannelManager) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }
 #[no_mangle]
 pub(crate) extern "C" fn ChannelManager_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
@@ -1670,7 +1694,7 @@ pub struct ChannelManagerReadArgs {
 impl Drop for ChannelManagerReadArgs {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeChannelManagerReadArgs>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -1683,11 +1707,17 @@ extern "C" fn ChannelManagerReadArgs_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelManagerReadArgs); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelManagerReadArgs {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeChannelManagerReadArgs {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelManagerReadArgs {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeChannelManagerReadArgs {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -1697,7 +1727,7 @@ impl ChannelManagerReadArgs {
 /// signing data.
 #[no_mangle]
 pub extern "C" fn ChannelManagerReadArgs_get_keys_manager(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::chain::keysinterface::KeysInterface {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.keys_manager;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().keys_manager;
        inner_val
 }
 /// The keys provider which will give us relevant keys. Some keys will be loaded during
@@ -1705,14 +1735,14 @@ pub extern "C" fn ChannelManagerReadArgs_get_keys_manager(this_ptr: &ChannelMana
 /// signing data.
 #[no_mangle]
 pub extern "C" fn ChannelManagerReadArgs_set_keys_manager(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::chain::keysinterface::KeysInterface) {
-       unsafe { &mut *this_ptr.inner }.keys_manager = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.keys_manager = val;
 }
 /// The fee_estimator for use in the ChannelManager in the future.
 ///
 /// No calls to the FeeEstimator will be made during deserialization.
 #[no_mangle]
 pub extern "C" fn ChannelManagerReadArgs_get_fee_estimator(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::chain::chaininterface::FeeEstimator {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.fee_estimator;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().fee_estimator;
        inner_val
 }
 /// The fee_estimator for use in the ChannelManager in the future.
@@ -1720,7 +1750,7 @@ pub extern "C" fn ChannelManagerReadArgs_get_fee_estimator(this_ptr: &ChannelMan
 /// No calls to the FeeEstimator will be made during deserialization.
 #[no_mangle]
 pub extern "C" fn ChannelManagerReadArgs_set_fee_estimator(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::chain::chaininterface::FeeEstimator) {
-       unsafe { &mut *this_ptr.inner }.fee_estimator = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.fee_estimator = val;
 }
 /// The chain::Watch for use in the ChannelManager in the future.
 ///
@@ -1729,7 +1759,7 @@ pub extern "C" fn ChannelManagerReadArgs_set_fee_estimator(this_ptr: &mut Channe
 /// chain::Watch after deserializing this ChannelManager.
 #[no_mangle]
 pub extern "C" fn ChannelManagerReadArgs_get_chain_monitor(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::chain::Watch {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.chain_monitor;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().chain_monitor;
        inner_val
 }
 /// The chain::Watch for use in the ChannelManager in the future.
@@ -1739,14 +1769,14 @@ pub extern "C" fn ChannelManagerReadArgs_get_chain_monitor(this_ptr: &ChannelMan
 /// chain::Watch after deserializing this ChannelManager.
 #[no_mangle]
 pub extern "C" fn ChannelManagerReadArgs_set_chain_monitor(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::chain::Watch) {
-       unsafe { &mut *this_ptr.inner }.chain_monitor = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.chain_monitor = val;
 }
 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
 /// used to broadcast the latest local commitment transactions of channels which must be
 /// force-closed during deserialization.
 #[no_mangle]
 pub extern "C" fn ChannelManagerReadArgs_get_tx_broadcaster(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::chain::chaininterface::BroadcasterInterface {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.tx_broadcaster;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().tx_broadcaster;
        inner_val
 }
 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
@@ -1754,33 +1784,33 @@ pub extern "C" fn ChannelManagerReadArgs_get_tx_broadcaster(this_ptr: &ChannelMa
 /// force-closed during deserialization.
 #[no_mangle]
 pub extern "C" fn ChannelManagerReadArgs_set_tx_broadcaster(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::chain::chaininterface::BroadcasterInterface) {
-       unsafe { &mut *this_ptr.inner }.tx_broadcaster = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.tx_broadcaster = val;
 }
 /// The Logger for use in the ChannelManager and which may be used to log information during
 /// deserialization.
 #[no_mangle]
 pub extern "C" fn ChannelManagerReadArgs_get_logger(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::util::logger::Logger {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.logger;
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().logger;
        inner_val
 }
 /// The Logger for use in the ChannelManager and which may be used to log information during
 /// deserialization.
 #[no_mangle]
 pub extern "C" fn ChannelManagerReadArgs_set_logger(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::util::logger::Logger) {
-       unsafe { &mut *this_ptr.inner }.logger = val;
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.logger = val;
 }
 /// Default settings used for new channels. Any existing channels will continue to use the
 /// runtime settings which were stored when the ChannelManager was serialized.
 #[no_mangle]
 pub extern "C" fn ChannelManagerReadArgs_get_default_config(this_ptr: &ChannelManagerReadArgs) -> crate::lightning::util::config::UserConfig {
-       let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.default_config;
-       crate::lightning::util::config::UserConfig { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false }
+       let mut inner_val = &mut this_ptr.get_native_mut_ref().default_config;
+       crate::lightning::util::config::UserConfig { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false }
 }
 /// Default settings used for new channels. Any existing channels will continue to use the
 /// runtime settings which were stored when the ChannelManager was serialized.
 #[no_mangle]
 pub extern "C" fn ChannelManagerReadArgs_set_default_config(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::util::config::UserConfig) {
-       unsafe { &mut *this_ptr.inner }.default_config = *unsafe { Box::from_raw(val.take_inner()) };
+       unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.default_config = *unsafe { Box::from_raw(val.take_inner()) };
 }
 /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
 /// HashMap for you. This is primarily useful for C bindings where it is not practical to
@@ -1788,9 +1818,9 @@ pub extern "C" fn ChannelManagerReadArgs_set_default_config(this_ptr: &mut Chann
 #[must_use]
 #[no_mangle]
 pub extern "C" fn ChannelManagerReadArgs_new(mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut chain_monitor: crate::lightning::chain::Watch, mut tx_broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut logger: crate::lightning::util::logger::Logger, mut default_config: crate::lightning::util::config::UserConfig, mut channel_monitors: crate::c_types::derived::CVec_ChannelMonitorZ) -> ChannelManagerReadArgs {
-       let mut local_channel_monitors = Vec::new(); for mut item in channel_monitors.into_rust().drain(..) { local_channel_monitors.push( { unsafe { &mut *item.inner } }); };
+       let mut local_channel_monitors = Vec::new(); for mut item in channel_monitors.into_rust().drain(..) { local_channel_monitors.push( { item.get_native_mut_ref() }); };
        let mut ret = lightning::ln::channelmanager::ChannelManagerReadArgs::new(keys_manager, fee_estimator, chain_monitor, tx_broadcaster, logger, *unsafe { Box::from_raw(default_config.take_inner()) }, local_channel_monitors);
-       ChannelManagerReadArgs { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       ChannelManagerReadArgs { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 #[no_mangle]
@@ -1798,6 +1828,6 @@ pub extern "C" fn ChannelManagerReadArgs_new(mut keys_manager: crate::lightning:
 pub extern "C" fn C2Tuple_BlockHashChannelManagerZ_read(ser: crate::c_types::u8slice, arg: crate::lightning::ln::channelmanager::ChannelManagerReadArgs) -> crate::c_types::derived::CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ {
        let arg_conv = *unsafe { Box::from_raw(arg.take_inner()) };
        let res: Result<(bitcoin::hash_types::BlockHash, lightning::ln::channelmanager::ChannelManager<crate::lightning::chain::keysinterface::Sign, crate::lightning::chain::Watch, crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::chain::keysinterface::KeysInterface, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::util::logger::Logger>), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
-       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_res_0_0, mut orig_res_0_1) = o; let mut local_res_0 = (crate::c_types::ThirtyTwoBytes { data: orig_res_0_0.into_inner() }, crate::lightning::ln::channelmanager::ChannelManager { inner: Box::into_raw(Box::new(orig_res_0_1)), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_res_0_0, mut orig_res_0_1) = o; let mut local_res_0 = (crate::c_types::ThirtyTwoBytes { data: orig_res_0_0.into_inner() }, crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(orig_res_0_1), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
        local_res
 }
index 8a61a8536c389dda9f542f075b0753922b7839e3..ba3d77949de83d760591254ba84eb8853cf23cc0 100644 (file)
@@ -41,7 +41,7 @@ use crate::c_types::*;
 pub extern "C" fn InitFeatures_eq(a: &InitFeatures, b: &InitFeatures) -> bool {
        if a.inner == b.inner { return true; }
        if a.inner.is_null() || b.inner.is_null() { return false; }
-       if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false }
+       if a.get_native_ref() == b.get_native_ref() { true } else { false }
 }
 /// Checks if two NodeFeaturess contain equal inner contents.
 /// This ignores pointers and is_owned flags and looks at the values in fields.
@@ -50,7 +50,7 @@ pub extern "C" fn InitFeatures_eq(a: &InitFeatures, b: &InitFeatures) -> bool {
 pub extern "C" fn NodeFeatures_eq(a: &NodeFeatures, b: &NodeFeatures) -> bool {
        if a.inner == b.inner { return true; }
        if a.inner.is_null() || b.inner.is_null() { return false; }
-       if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false }
+       if a.get_native_ref() == b.get_native_ref() { true } else { false }
 }
 /// Checks if two ChannelFeaturess contain equal inner contents.
 /// This ignores pointers and is_owned flags and looks at the values in fields.
@@ -59,7 +59,7 @@ pub extern "C" fn NodeFeatures_eq(a: &NodeFeatures, b: &NodeFeatures) -> bool {
 pub extern "C" fn ChannelFeatures_eq(a: &ChannelFeatures, b: &ChannelFeatures) -> bool {
        if a.inner == b.inner { return true; }
        if a.inner.is_null() || b.inner.is_null() { return false; }
-       if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false }
+       if a.get_native_ref() == b.get_native_ref() { true } else { false }
 }
 /// Checks if two InvoiceFeaturess contain equal inner contents.
 /// This ignores pointers and is_owned flags and looks at the values in fields.
@@ -68,13 +68,13 @@ pub extern "C" fn ChannelFeatures_eq(a: &ChannelFeatures, b: &ChannelFeatures) -
 pub extern "C" fn InvoiceFeatures_eq(a: &InvoiceFeatures, b: &InvoiceFeatures) -> bool {
        if a.inner == b.inner { return true; }
        if a.inner.is_null() || b.inner.is_null() { return false; }
-       if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false }
+       if a.get_native_ref() == b.get_native_ref() { true } else { false }
 }
 impl Clone for InitFeatures {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeInitFeatures>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -93,7 +93,7 @@ impl Clone for NodeFeatures {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeNodeFeatures>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -112,7 +112,7 @@ impl Clone for ChannelFeatures {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeChannelFeatures>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -131,7 +131,7 @@ impl Clone for InvoiceFeatures {
        fn clone(&self) -> Self {
                Self {
                        inner: if <*mut nativeInvoiceFeatures>::is_null(self.inner) { std::ptr::null_mut() } else {
-                               Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
+                               ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
        }
@@ -169,7 +169,7 @@ pub struct InitFeatures {
 impl Drop for InitFeatures {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeInitFeatures>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -182,11 +182,17 @@ extern "C" fn InitFeatures_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInitFeatures); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl InitFeatures {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeInitFeatures {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeInitFeatures {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeInitFeatures {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -214,7 +220,7 @@ pub struct NodeFeatures {
 impl Drop for NodeFeatures {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeNodeFeatures>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -227,11 +233,17 @@ extern "C" fn NodeFeatures_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeNodeFeatures); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl NodeFeatures {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeNodeFeatures {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeNodeFeatures {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeNodeFeatures {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -259,7 +271,7 @@ pub struct ChannelFeatures {
 impl Drop for ChannelFeatures {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeChannelFeatures>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -272,11 +284,17 @@ extern "C" fn ChannelFeatures_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelFeatures); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl ChannelFeatures {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeChannelFeatures {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelFeatures {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeChannelFeatures {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -304,7 +322,7 @@ pub struct InvoiceFeatures {
 impl Drop for InvoiceFeatures {
        fn drop(&mut self) {
                if self.is_owned && !<*mut nativeInvoiceFeatures>::is_null(self.inner) {
-                       let _ = unsafe { Box::from_raw(self.inner) };
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
                }
        }
 }
@@ -317,11 +335,17 @@ extern "C" fn InvoiceFeatures_free_void(this_ptr: *mut c_void) {
        unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInvoiceFeatures); }
 }
 #[allow(unused)]
-/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
 impl InvoiceFeatures {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeInvoiceFeatures {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeInvoiceFeatures {
+               unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
+       }
+       /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
        pub(crate) fn take_inner(mut self) -> *mut nativeInvoiceFeatures {
                assert!(self.is_owned);
-               let ret = self.inner;
+               let ret = ObjOps::untweak_ptr(self.inner);
                self.inner = std::ptr::null_mut();
                ret
        }
@@ -331,7 +355,7 @@ impl InvoiceFeatures {
 #[no_mangle]
 pub extern "C" fn InitFeatures_empty() -> InitFeatures {
        let mut ret = lightning::ln::features::InitFeatures::empty();
-       InitFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       InitFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 /// Creates a Features with the bits set which are known by the implementation
@@ -339,7 +363,7 @@ pub extern "C" fn InitFeatures_empty() -> InitFeatures {
 #[no_mangle]
 pub extern "C" fn InitFeatures_known() -> InitFeatures {
        let mut ret = lightning::ln::features::InitFeatures::known();
-       InitFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       InitFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 /// Create a blank Features with no features set
@@ -347,7 +371,7 @@ pub extern "C" fn InitFeatures_known() -> InitFeatures {
 #[no_mangle]
 pub extern "C" fn NodeFeatures_empty() -> NodeFeatures {
        let mut ret = lightning::ln::features::NodeFeatures::empty();
-       NodeFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       NodeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 /// Creates a Features with the bits set which are known by the implementation
@@ -355,7 +379,7 @@ pub extern "C" fn NodeFeatures_empty() -> NodeFeatures {
 #[no_mangle]
 pub extern "C" fn NodeFeatures_known() -> NodeFeatures {
        let mut ret = lightning::ln::features::NodeFeatures::known();
-       NodeFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       NodeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 /// Create a blank Features with no features set
@@ -363,7 +387,7 @@ pub extern "C" fn NodeFeatures_known() -> NodeFeatures {
 #[no_mangle]
 pub extern "C" fn ChannelFeatures_empty() -> ChannelFeatures {
        let mut ret = lightning::ln::features::ChannelFeatures::empty();
-       ChannelFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       ChannelFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 /// Creates a Features with the bits set which are known by the implementation
@@ -371,7 +395,7 @@ pub extern "C" fn ChannelFeatures_empty() -> ChannelFeatures {
 #[no_mangle]
 pub extern "C" fn ChannelFeatures_known() -> ChannelFeatures {
        let mut ret = lightning::ln::features::ChannelFeatures::known();
-       ChannelFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       ChannelFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 /// Create a blank Features with no features set
@@ -379,7 +403,7 @@ pub extern "C" fn ChannelFeatures_known() -> ChannelFeatures {
 #[no_mangle]
 pub extern "C" fn InvoiceFeatures_empty() -> InvoiceFeatures {
        let mut ret = lightning::ln::features::InvoiceFeatures::empty();
-       InvoiceFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       InvoiceFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 /// Creates a Features with the bits set which are known by the implementation
@@ -387,14 +411,14 @@ pub extern "C" fn InvoiceFeatures_empty() -> InvoiceFeatures {
 #[no_mangle]
 pub extern "C" fn InvoiceFeatures_known() -> InvoiceFeatures {
        let mut ret = lightning::ln::features::InvoiceFeatures::known();
-       InvoiceFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true }
+       InvoiceFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
 }
 
 /// Returns whether the `payment_secret` feature is supported.
 #[must_use]
 #[no_mangle]
 pub extern "C" fn InitFeatures_supports_payment_secret(this_arg: &InitFeatures) -> bool {
-       let mut ret = unsafe { &*this_arg.inner }.supports_payment_secret();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.supports_payment_secret();
        ret
 }
 
@@ -402,7 +426,7 @@ pub extern "C" fn InitFeatures_supports_payment_secret(this_arg: &InitFeatures)
 #[must_use]
 #[no_mangle]
 pub extern "C" fn NodeFeatures_supports_payment_secret(this_arg: &NodeFeatures) -> bool {
-       let mut ret = unsafe { &*this_arg.inner }.supports_payment_secret();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.supports_payment_secret();
        ret
 }
 
@@ -410,14 +434,14 @@ pub extern "C" fn NodeFeatures_supports_payment_secret(this_arg: &NodeFeatures)
 #[must_use]
 #[no_mangle]
 pub extern "C" fn InvoiceFeatures_supports_payment_secret(this_arg: &InvoiceFeatures) -> bool {
-       let mut ret = unsafe { &*this_arg.inner }.supports_payment_secret();
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.supports_payment_secret();
        ret
 }
 
 #[no_mangle]
 /// Serialize the InitFeatures object into a byte array which can be read by InitFeatures_read
 pub extern "C" fn InitFeatures_write(obj: &InitFeatures) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }
 #[no_mangle]
 pub(crate) extern "C" fn InitFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
@@ -426,7 +450,7 @@ pub(crate) extern "C" fn InitFeatures_write_void(obj: *const c_void) -> crate::c
 #[no_mangle]
 /// Serialize the NodeFeatures object into a byte array which can be read by NodeFeatures_read
 pub extern "C" fn NodeFeatures_write(obj: &NodeFeatures) -> crate::c_types::derived::CVec_u8Z {
-       crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
 }