Figure out java human types conversion stuff when doing all conv
[ldk-java] / genbindings.py
index 27b31525f61ebbc9ad780fdcba8b84b8ef53583b..b1965938a6805e14d40950f50d2d4a5e48b73858 100755 (executable)
@@ -7,9 +7,10 @@ if len(sys.argv) != 6:
     sys.exit(1)
 
 class TypeInfo:
-    def __init__(self, rust_obj, java_ty, java_fn_ty_arg, c_ty, passed_as_ptr, is_ptr, var_name, arr_len, arr_access):
+    def __init__(self, rust_obj, java_ty, java_fn_ty_arg, java_hu_ty, c_ty, passed_as_ptr, is_ptr, var_name, arr_len, arr_access):
         self.rust_obj = rust_obj
         self.java_ty = java_ty
+        self.java_hu_ty = java_hu_ty
         self.java_fn_ty_arg = java_fn_ty_arg
         self.c_ty = c_ty
         self.passed_as_ptr = passed_as_ptr
@@ -19,7 +20,7 @@ class TypeInfo:
         self.arr_access = arr_access
 
 class ConvInfo:
-    def __init__(self, ty_info, arg_name, arg_conv, arg_conv_name, ret_conv, ret_conv_name):
+    def __init__(self, ty_info, arg_name, arg_conv, arg_conv_name, arg_conv_cleanup, ret_conv, ret_conv_name, to_hu_conv, from_hu_conv):
         assert(ty_info.c_ty is not None)
         assert(ty_info.java_ty is not None)
         assert(arg_name is not None)
@@ -27,12 +28,16 @@ class ConvInfo:
         self.rust_obj = ty_info.rust_obj
         self.c_ty = ty_info.c_ty
         self.java_ty = ty_info.java_ty
+        self.java_hu_ty = ty_info.java_hu_ty
         self.java_fn_ty_arg = ty_info.java_fn_ty_arg
         self.arg_name = arg_name
         self.arg_conv = arg_conv
         self.arg_conv_name = arg_conv_name
+        self.arg_conv_cleanup = arg_conv_cleanup
         self.ret_conv = ret_conv
         self.ret_conv_name = ret_conv_name
+        self.to_hu_conv = to_hu_conv
+        self.from_hu_conv = from_hu_conv
 
     def print_ty(self):
         out_c.write(self.c_ty)
@@ -45,180 +50,202 @@ class ConvInfo:
         else:
             out_java.write(" arg")
             out_c.write(" arg")
+
+def camel_to_snake(s):
+    # Convert camel case to snake case, in a way that appears to match cbindgen
+    con = "_"
+    ret = ""
+    lastchar = ""
+    lastund = False
+    for char in s:
+        if lastchar.isupper():
+            if not char.isupper() and not lastund:
+                ret = ret + "_"
+                lastund = True
+            else:
+                lastund = False
+            ret = ret + lastchar.lower()
+        else:
+            ret = ret + lastchar
+            if char.isupper() and not lastund:
+                ret = ret + "_"
+                lastund = True
+            else:
+                lastund = False
+        lastchar = char
+        if char.isnumeric():
+            lastund = True
+    return (ret + lastchar.lower()).strip("_")
+
+unitary_enums = set()
+opaque_structs = set()
+trait_structs = set()
+
+var_is_arr_regex = re.compile("\(\*([A-za-z0-9_]*)\)\[([a-z0-9]*)\]")
+var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
+def java_c_types(fn_arg, ret_arr_len):
+    fn_arg = fn_arg.strip()
+    if fn_arg.startswith("MUST_USE_RES "):
+        fn_arg = fn_arg[13:]
+    is_const = False
+    if fn_arg.startswith("const "):
+        fn_arg = fn_arg[6:]
+        is_const = True
+
+    is_ptr = False
+    take_by_ptr = False
+    rust_obj = None
+    arr_access = None
+    java_hu_ty = None
+    if fn_arg.startswith("LDKThirtyTwoBytes"):
+        fn_arg = "uint8_t (*" + fn_arg[18:] + ")[32]"
+        assert var_is_arr_regex.match(fn_arg[8:])
+        rust_obj = "LDKThirtyTwoBytes"
+        arr_access = "data"
+    if fn_arg.startswith("LDKPublicKey"):
+        fn_arg = "uint8_t (*" + fn_arg[13:] + ")[33]"
+        assert var_is_arr_regex.match(fn_arg[8:])
+        rust_obj = "LDKPublicKey"
+        arr_access = "compressed_form"
+    if fn_arg.startswith("LDKSecretKey"):
+        fn_arg = "uint8_t (*" + fn_arg[13:] + ")[32]"
+        assert var_is_arr_regex.match(fn_arg[8:])
+        rust_obj = "LDKSecretKey"
+        arr_access = "bytes"
+    if fn_arg.startswith("LDKSignature"):
+        fn_arg = "uint8_t (*" + fn_arg[13:] + ")[64]"
+        assert var_is_arr_regex.match(fn_arg[8:])
+        rust_obj = "LDKSignature"
+        arr_access = "compact_form"
+    if fn_arg.startswith("LDKThreeBytes"):
+        fn_arg = "uint8_t (*" + fn_arg[14:] + ")[3]"
+        assert var_is_arr_regex.match(fn_arg[8:])
+        rust_obj = "LDKThreeBytes"
+        arr_access = "data"
+    if fn_arg.startswith("LDKu8slice"):
+        fn_arg = "uint8_t (*" + fn_arg[11:] + ")[datalen]"
+        assert var_is_arr_regex.match(fn_arg[8:])
+        rust_obj = "LDKu8slice"
+        arr_access = "data"
+    if fn_arg.startswith("LDKCVecTempl_u8"):
+        fn_arg = "uint8_t (*" + fn_arg[11:] + ")[datalen]"
+        assert var_is_arr_regex.match(fn_arg[8:])
+        rust_obj = "LDKCVecTempl_u8"
+        arr_access = "data"
+
+    if fn_arg.startswith("void"):
+        java_ty = "void"
+        c_ty = "void"
+        fn_ty_arg = "V"
+        fn_arg = fn_arg[4:].strip()
+    elif fn_arg.startswith("bool"):
+        java_ty = "boolean"
+        c_ty = "jboolean"
+        fn_ty_arg = "Z"
+        fn_arg = fn_arg[4:].strip()
+    elif fn_arg.startswith("uint8_t"):
+        java_ty = "byte"
+        c_ty = "jbyte"
+        fn_ty_arg = "B"
+        fn_arg = fn_arg[7:].strip()
+    elif fn_arg.startswith("uint16_t"):
+        java_ty = "short"
+        c_ty = "jshort"
+        fn_ty_arg = "S"
+        fn_arg = fn_arg[8:].strip()
+    elif fn_arg.startswith("uint32_t"):
+        java_ty = "int"
+        c_ty = "jint"
+        fn_ty_arg = "I"
+        fn_arg = fn_arg[8:].strip()
+    elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
+        java_ty = "long"
+        c_ty = "jlong"
+        fn_ty_arg = "J"
+        if fn_arg.startswith("uint64_t"):
+            fn_arg = fn_arg[8:].strip()
+        else:
+            fn_arg = fn_arg[9:].strip()
+    elif is_const and fn_arg.startswith("char *"):
+        java_ty = "String"
+        c_ty = "const char*"
+        fn_ty_arg = "Ljava/lang/String;"
+        fn_arg = fn_arg[6:].strip()
+    else:
+        ma = var_ty_regex.match(fn_arg)
+        if ma.group(1).strip() in unitary_enums:
+            java_ty = ma.group(1).strip()
+            c_ty = "jclass"
+            fn_ty_arg = "Lorg/ldk/enums/" + ma.group(1).strip() + ";"
+            fn_arg = ma.group(2).strip()
+            rust_obj = ma.group(1).strip()
+            take_by_ptr = True
+        else:
+            java_ty = "long"
+            java_hu_ty = ma.group(1).strip().replace("LDK", "")
+            c_ty = "jlong"
+            fn_ty_arg = "J"
+            fn_arg = ma.group(2).strip()
+            rust_obj = ma.group(1).strip()
+            take_by_ptr = True
+
+    if fn_arg.startswith(" *") or fn_arg.startswith("*"):
+        fn_arg = fn_arg.replace("*", "").strip()
+        is_ptr = True
+        c_ty = "jlong"
+        java_ty = "long"
+        fn_ty_arg = "J"
+
+    var_is_arr = var_is_arr_regex.match(fn_arg)
+    if var_is_arr is not None or ret_arr_len is not None:
+        assert(not take_by_ptr)
+        assert(not is_ptr)
+        java_ty = java_ty + "[]"
+        c_ty = c_ty + "Array"
+        if var_is_arr is not None:
+            if var_is_arr.group(1) == "":
+                return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_hu_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
+                    passed_as_ptr=False, is_ptr=False, var_name="arg", arr_len=var_is_arr.group(2), arr_access=arr_access)
+            return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_hu_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
+                passed_as_ptr=False, is_ptr=False, var_name=var_is_arr.group(1), arr_len=var_is_arr.group(2), arr_access=arr_access)
+
+    if java_hu_ty is None:
+        java_hu_ty = java_ty
+    return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_hu_ty=java_hu_ty, java_fn_ty_arg=fn_ty_arg, c_ty=c_ty, passed_as_ptr=is_ptr or take_by_ptr,
+        is_ptr=is_ptr, var_name=fn_arg, arr_len=None, arr_access=None)
+
 fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
 fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
 reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
 clone_fns = set()
+constructor_fns = {}
 with open(sys.argv[1]) as in_h:
     for line in in_h:
         reg_fn = reg_fn_regex.match(line)
         if reg_fn is not None:
             if reg_fn.group(2).endswith("_clone"):
                 clone_fns.add(reg_fn.group(2))
+            else:
+                rty = java_c_types(reg_fn.group(1), None)
+                if rty.rust_obj is not None and reg_fn.group(2) == rty.java_hu_ty + "_new":
+                    constructor_fns[rty.rust_obj] = reg_fn.group(3)
             continue
         arr_fn = fn_ret_arr_regex.match(line)
         if arr_fn is not None:
             if arr_fn.group(2).endswith("_clone"):
                 clone_fns.add(arr_fn.group(2))
+            # No object constructors return arrays, as then they wouldn't be an object constructor
             continue
 
 with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.argv[4], "w") as out_c:
-    opaque_structs = set()
-    trait_structs = set()
-    unitary_enums = set()
-
-    def camel_to_snake(s):
-        # Convert camel case to snake case, in a way that appears to match cbindgen
-        con = "_"
-        ret = ""
-        lastchar = ""
-        lastund = False
-        for char in s:
-            if lastchar.isupper():
-                if not char.isupper() and not lastund:
-                    ret = ret + "_"
-                    lastund = True
-                else:
-                    lastund = False
-                ret = ret + lastchar.lower()
-            else:
-                ret = ret + lastchar
-                if char.isupper() and not lastund:
-                    ret = ret + "_"
-                    lastund = True
-                else:
-                    lastund = False
-            lastchar = char
-            if char.isnumeric():
-                lastund = True
-        return (ret + lastchar.lower()).strip("_")
-
-    var_is_arr_regex = re.compile("\(\*([A-za-z0-9_]*)\)\[([0-9]*)\]")
-    var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
-    def java_c_types(fn_arg, ret_arr_len):
-        fn_arg = fn_arg.strip()
-        if fn_arg.startswith("MUST_USE_RES "):
-            fn_arg = fn_arg[13:]
-        is_const = False
-        if fn_arg.startswith("const "):
-            fn_arg = fn_arg[6:]
-            is_const = True
-
-        is_ptr = False
-        take_by_ptr = False
-        rust_obj = None
-        arr_access = None
-        if fn_arg.startswith("LDKThirtyTwoBytes"):
-            fn_arg = "uint8_t (*" + fn_arg[18:] + ")[32]"
-            assert var_is_arr_regex.match(fn_arg[8:])
-            rust_obj = "LDKThirtyTwoBytes"
-            arr_access = "data"
-        if fn_arg.startswith("LDKPublicKey"):
-            fn_arg = "uint8_t (*" + fn_arg[13:] + ")[33]"
-            assert var_is_arr_regex.match(fn_arg[8:])
-            rust_obj = "LDKPublicKey"
-            arr_access = "compressed_form"
-        if fn_arg.startswith("LDKSecretKey"):
-            fn_arg = "uint8_t (*" + fn_arg[13:] + ")[32]"
-            assert var_is_arr_regex.match(fn_arg[8:])
-            rust_obj = "LDKSecretKey"
-            arr_access = "bytes"
-        if fn_arg.startswith("LDKSignature"):
-            fn_arg = "uint8_t (*" + fn_arg[13:] + ")[64]"
-            assert var_is_arr_regex.match(fn_arg[8:])
-            rust_obj = "LDKSignature"
-            arr_access = "compact_form"
-        if fn_arg.startswith("LDKThreeBytes"):
-            fn_arg = "uint8_t (*" + fn_arg[14:] + ")[3]"
-            assert var_is_arr_regex.match(fn_arg[8:])
-            rust_obj = "LDKThreeBytes"
-            arr_access = "data"
-
-        if fn_arg.startswith("void"):
-            java_ty = "void"
-            c_ty = "void"
-            fn_ty_arg = "V"
-            fn_arg = fn_arg[4:].strip()
-        elif fn_arg.startswith("bool"):
-            java_ty = "boolean"
-            c_ty = "jboolean"
-            fn_ty_arg = "Z"
-            fn_arg = fn_arg[4:].strip()
-        elif fn_arg.startswith("uint8_t"):
-            java_ty = "byte"
-            c_ty = "jbyte"
-            fn_ty_arg = "B"
-            fn_arg = fn_arg[7:].strip()
-        elif fn_arg.startswith("uint16_t"):
-            java_ty = "short"
-            c_ty = "jshort"
-            fn_ty_arg = "S"
-            fn_arg = fn_arg[8:].strip()
-        elif fn_arg.startswith("uint32_t"):
-            java_ty = "int"
-            c_ty = "jint"
-            fn_ty_arg = "I"
-            fn_arg = fn_arg[8:].strip()
-        elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
-            java_ty = "long"
-            c_ty = "jlong"
-            fn_ty_arg = "J"
-            if fn_arg.startswith("uint64_t"):
-                fn_arg = fn_arg[8:].strip()
-            else:
-                fn_arg = fn_arg[9:].strip()
-        elif is_const and fn_arg.startswith("char *"):
-            java_ty = "String"
-            c_ty = "const char*"
-            fn_ty_arg = "Ljava/lang/String;"
-            fn_arg = fn_arg[6:].strip()
-        else:
-            ma = var_ty_regex.match(fn_arg)
-            if ma.group(1).strip() in unitary_enums:
-                java_ty = ma.group(1).strip()
-                c_ty = "jclass"
-                fn_ty_arg = "Lorg/ldk/enums/" + ma.group(1).strip() + ";"
-                fn_arg = ma.group(2).strip()
-                rust_obj = ma.group(1).strip()
-                take_by_ptr = True
-            else:
-                java_ty = "long"
-                c_ty = "jlong"
-                fn_ty_arg = "J"
-                fn_arg = ma.group(2).strip()
-                rust_obj = ma.group(1).strip()
-                take_by_ptr = True
-
-        if fn_arg.startswith(" *") or fn_arg.startswith("*"):
-            fn_arg = fn_arg.replace("*", "").strip()
-            is_ptr = True
-            c_ty = "jlong"
-            java_ty = "long"
-            fn_ty_arg = "J"
-
-        var_is_arr = var_is_arr_regex.match(fn_arg)
-        if var_is_arr is not None or ret_arr_len is not None:
-            assert(not take_by_ptr)
-            assert(not is_ptr)
-            java_ty = java_ty + "[]"
-            c_ty = c_ty + "Array"
-            if var_is_arr is not None:
-                if var_is_arr.group(1) == "":
-                    return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
-                        passed_as_ptr=False, is_ptr=False, var_name="arg", arr_len=var_is_arr.group(2), arr_access=arr_access)
-                return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
-                    passed_as_ptr=False, is_ptr=False, var_name=var_is_arr.group(1), arr_len=var_is_arr.group(2), arr_access=arr_access)
-        return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_fn_ty_arg=fn_ty_arg, c_ty=c_ty, passed_as_ptr=is_ptr or take_by_ptr,
-            is_ptr=is_ptr, var_name=fn_arg, arr_len=None, arr_access=None)
-
     def map_type(fn_arg, print_void, ret_arr_len, is_free):
         ty_info = java_c_types(fn_arg, ret_arr_len)
 
         if ty_info.c_ty == "void":
             if not print_void:
                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
-                    arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
-
+                    arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
+                    ret_conv = None, ret_conv_name = None, to_hu_conv = None, from_hu_conv = None)
         if ty_info.c_ty.endswith("Array"):
             arr_len = ty_info.arr_len
             if arr_len is not None:
@@ -227,23 +254,30 @@ with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.arg
                 arr_name = "ret"
                 arr_len = ret_arr_len
             assert(ty_info.c_ty == "jbyteArray")
-            if ty_info.rust_obj is not None:
+            ret_conv = ("jbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_len + ");\n" + "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_len + ", ", "")
+            arg_conv_cleanup = None
+            if not arr_len.isdigit():
+                arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n"
+                arg_conv = arg_conv + arr_name + "_ref." + ty_info.arr_access + " = (*_env)->GetByteArrayElements (_env, " + arr_name + ", NULL);\n"
+                arg_conv = arg_conv + arr_name + "_ref." + arr_len + " = (*_env)->GetArrayLength (_env, " + arr_name + ");"
+                arg_conv_cleanup = "(*_env)->ReleaseByteArrayElements(_env, " + arr_name + ", (int8_t*)" + arr_name + "_ref." + ty_info.arr_access + ", 0);"
+                arr_access = "." + ty_info.arr_access
+                ret_conv = (ty_info.rust_obj + " " + arr_name + "_var = ", "")
+                ret_conv = (ret_conv[0], ";\njbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_name + "_var." + arr_len + ");\n")
+                ret_conv = (ret_conv[0], ret_conv[1] + "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_name + "_var." + arr_len + ", " + arr_name + "_var." + ty_info.arr_access + ");")
+            elif ty_info.rust_obj is not None:
                 arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n"
                 arg_conv = arg_conv + "CHECK((*_env)->GetArrayLength (_env, " + arr_name + ") == " + arr_len + ");\n"
                 arg_conv = arg_conv + "(*_env)->GetByteArrayRegion (_env, " + arr_name + ", 0, " + arr_len + ", " + arr_name + "_ref." + ty_info.arr_access + ");"
-                arr_access = ("", "." + ty_info.arr_access)
+                ret_conv = (ret_conv[0], "." + ty_info.arr_access + ");")
             else:
                 arg_conv = "unsigned char " + arr_name + "_arr[" + arr_len + "];\n"
                 arg_conv = arg_conv + "CHECK((*_env)->GetArrayLength (_env, " + arr_name + ") == " + arr_len + ");\n"
                 arg_conv = arg_conv + "(*_env)->GetByteArrayRegion (_env, " + arr_name + ", 0, " + arr_len + ", " + arr_name + "_arr);\n" + "unsigned char (*" + arr_name + "_ref)[" + arr_len + "] = &" + arr_name + "_arr;"
-                arr_access = ("*", "")
+                ret_conv = (ret_conv[0] + "*", ");")
             return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
-                arg_conv = arg_conv,
-                arg_conv_name = arr_name + "_ref",
-                ret_conv = ("jbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_len + ");\n" +
-                    "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_len + ", " + arr_access[0],
-                    arr_access[1] + ");"),
-                ret_conv_name = arr_name + "_arr")
+                arg_conv = arg_conv, arg_conv_name = arr_name + "_ref", arg_conv_cleanup = arg_conv_cleanup,
+                ret_conv = ret_conv, ret_conv_name = arr_name + "_arr", to_hu_conv = None, from_hu_conv = None)
         elif ty_info.var_name != "":
             # If we have a parameter name, print it (noting that it may indicate its a pointer)
             if ty_info.rust_obj is not None:
@@ -252,10 +286,10 @@ with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.arg
                 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.inner = (void*)(" + ty_info.var_name + " & (~1));\n"
                 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.is_owned = (" + ty_info.var_name + " & 1) || (" + ty_info.var_name + " == 0);"
                 if not ty_info.is_ptr and not is_free:
-                    if (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
+                    if (ty_info.java_hu_ty + "_clone") in clone_fns:
                         # TODO: This is a bit too naive, even with the checks above, we really need to know if rust wants a ref or not, not just if its pass as a ptr.
                         opaque_arg_conv = opaque_arg_conv + "\nif (" + ty_info.var_name + "_conv.inner != NULL)\n"
-                        opaque_arg_conv = opaque_arg_conv + "\t" + ty_info.var_name + "_conv = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&" + ty_info.var_name + "_conv);"
+                        opaque_arg_conv = opaque_arg_conv + "\t" + ty_info.var_name + "_conv = " + ty_info.java_hu_ty + "_clone(&" + ty_info.var_name + "_conv);"
                     elif ty_info.passed_as_ptr:
                         opaque_arg_conv = opaque_arg_conv + "\n// Warning: we may need a move here but can't clone!"
                 if not ty_info.is_ptr:
@@ -263,8 +297,9 @@ with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.arg
                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
                             arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
                             arg_conv_name = ty_info.var_name + "_conv",
+                            arg_conv_cleanup = None,
                             ret_conv = ("jclass " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_to_java(_env, ", ");"),
-                            ret_conv_name = ty_info.var_name + "_conv")
+                            ret_conv_name = ty_info.var_name + "_conv", to_hu_conv = None, from_hu_conv = None)
                     if ty_info.rust_obj in opaque_structs:
                         ret_conv_suf = ";\nCHECK((((long)" + ty_info.var_name + "_var.inner) & 1) == 0); // We rely on a free low bit, malloc guarantees this.\n"
                         ret_conv_suf = ret_conv_suf + "CHECK((((long)&" + ty_info.var_name + "_var) & 1) == 0); // We rely on a free low bit, pointer alignment guarantees this.\n"
@@ -275,9 +310,10 @@ with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.arg
                         ret_conv_suf = ret_conv_suf + "\t" + ty_info.var_name + "_ref = (long)&" + ty_info.var_name + "_var;\n"
                         ret_conv_suf = ret_conv_suf + "}"
                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
-                            arg_conv = opaque_arg_conv, arg_conv_name = ty_info.var_name + "_conv",
+                            arg_conv = opaque_arg_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
                             ret_conv = (ty_info.rust_obj + " " + ty_info.var_name + "_var = ", ret_conv_suf),
-                            ret_conv_name = ty_info.var_name + "_ref")
+                            ret_conv_name = ty_info.var_name + "_ref", to_hu_conv = ("new " + ty_info.java_hu_ty + "(null, ", ")"),
+                            from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")"))
                     base_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = *(" + ty_info.rust_obj + "*)" + ty_info.var_name + ";";
                     if ty_info.rust_obj in trait_structs:
                         if not is_free:
@@ -287,48 +323,60 @@ with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.arg
                         else:
                             base_conv = base_conv + "\n" + "FREE((void*)" + ty_info.var_name + ");"
                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
-                            arg_conv = base_conv,
-                            arg_conv_name = ty_info.var_name + "_conv",
-                            ret_conv = ("CANT PASS TRAIT TO Java?", ""), ret_conv_name = "NO CONV POSSIBLE")
+                            arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
+                            ret_conv = ("CANT PASS TRAIT TO Java?", ""), ret_conv_name = "NO CONV POSSIBLE",
+                            to_hu_conv = ("DUMMY", ""), from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr", "this.ptrs_to.add(" + ty_info.var_name + ")"))
                     if ty_info.rust_obj != "LDKu8slice":
                         # Don't bother free'ing slices passed in - Rust doesn't auto-free the
                         # underlying unlike Vecs, and it gives Java more freedom.
                         base_conv = base_conv + "\nFREE((void*)" + ty_info.var_name + ");";
                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
-                        arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv",
-                        ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref")
+                        arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
+                        ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref",
+                        to_hu_conv = ("TODO 1", ""), from_hu_conv = None)
                 else:
                     assert(not is_free)
                     if ty_info.rust_obj in opaque_structs:
                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
-                            arg_conv = opaque_arg_conv, arg_conv_name = "&" + ty_info.var_name + "_conv",
-                            ret_conv = None, ret_conv_name = None) # its a pointer, no conv needed
+                            arg_conv = opaque_arg_conv, arg_conv_name = "&" + ty_info.var_name + "_conv", arg_conv_cleanup = None,
+                            ret_conv = None, ret_conv_name = None, to_hu_conv = ("TODO 2", ""),
+                            from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")")) # its a pointer, no conv needed
+                    elif ty_info.rust_obj in trait_structs:
+                        return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
+                            arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
+                            arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
+                            ret_conv = None, ret_conv_name = None, to_hu_conv = ("TODO 2.5", ""),
+                            from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr", "this.ptrs_to.add(" + ty_info.var_name + ")")) # its a pointer, no conv needed
                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
                         arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
-                        arg_conv_name = ty_info.var_name + "_conv",
-                        ret_conv = None, ret_conv_name = None) # its a pointer, no conv needed
+                        arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
+                        ret_conv = None, ret_conv_name = None, to_hu_conv = ("TODO 3", ""), from_hu_conv = None) # its a pointer, no conv needed
             elif ty_info.is_ptr:
                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
-                    arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
+                    arg_conv = None, arg_conv_name = ty_info.var_name, arg_conv_cleanup = None,
+                    ret_conv = None, ret_conv_name = None, to_hu_conv = ("TODO 4", ""), from_hu_conv = None)
             elif ty_info.java_ty == "String":
                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
-                    arg_conv = None, arg_conv_name = None,
-                    ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv")
+                    arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
+                    ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv",
+                    to_hu_conv = ("TODO 5", ""), from_hu_conv = None)
             else:
                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
-                    arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
+                    arg_conv = None, arg_conv_name = ty_info.var_name, arg_conv_cleanup = None,
+                    ret_conv = None, ret_conv_name = None, to_hu_conv = ("TODO 6", ""), from_hu_conv = None)
         elif not print_void:
             # We don't have a parameter name, and want one, just call it arg
             if ty_info.rust_obj is not None:
                 assert(not is_free or ty_info.rust_obj not in opaque_structs);
                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
                     arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nFREE((void*)arg);",
-                    arg_conv_name = "arg_conv",
-                    ret_conv = None, ret_conv_name = None)
+                    arg_conv_name = "arg_conv", arg_conv_cleanup = None,
+                    ret_conv = None, ret_conv_name = None, to_hu_conv = ("TODO 7", ""), from_hu_conv = None)
             else:
                 assert(not is_free)
                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
-                    arg_conv = None, arg_conv_name = "arg", ret_conv = None, ret_conv_name = None)
+                    arg_conv = None, arg_conv_name = "arg", arg_conv_cleanup = None,
+                    ret_conv = None, ret_conv_name = None, to_hu_conv = ("TODO 8", ""), from_hu_conv = None)
         else:
             # We don't have a parameter name, and don't want one (cause we're returning)
             if ty_info.rust_obj is not None:
@@ -336,8 +384,9 @@ with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.arg
                     if ty_info.rust_obj in unitary_enums:
                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
                             arg_conv = ty_info.rust_obj + " ret = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
-                            arg_conv_name = "ret",
-                            ret_conv = ("jclass ret = " + ty_info.rust_obj + "_to_java(_env, ", ");"), ret_conv_name = "ret")
+                            arg_conv_name = "ret", arg_conv_cleanup = None,
+                            ret_conv = ("jclass ret = " + ty_info.rust_obj + "_to_java(_env, ", ");"), ret_conv_name = "ret",
+                            to_hu_conv = ("TODO 9", ""), from_hu_conv = None)
                     if ty_info.rust_obj in opaque_structs:
                         # If we're returning a newly-allocated struct, we don't want Rust to ever
                         # free, instead relying on the Java GC to lose the ref. We undo this in
@@ -346,19 +395,35 @@ with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.arg
                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
                             ret_conv = (ty_info.rust_obj + " ret = ", ";"),
                             ret_conv_name = "((long)ret.inner) | (ret.is_owned ? 1 : 0)",
-                            arg_conv = None, arg_conv_name = None)
+                            arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
+                            to_hu_conv = ("new " + ty_info.java_hu_ty + "(null, ", ")"), from_hu_conv = None)
+                    elif ty_info.rust_obj in trait_structs:
+                        return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
+                            ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
+                            ret_conv_name = "(long)ret",
+                            arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
+                            to_hu_conv = ("new " + ty_info.java_hu_ty + "(null, ", ");\nret.ptrs_to.add(this)"), from_hu_conv = None)
                     else:
                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
                             ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
                             ret_conv_name = "(long)ret",
-                            arg_conv = None, arg_conv_name = None)
+                            arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
+                            to_hu_conv = ("TODO b", ""), from_hu_conv = None)
+                elif ty_info.rust_obj in trait_structs:
+                    return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
+                        ret_conv = ("long ret = (long)", ";"), ret_conv_name = "ret",
+                        arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
+                        to_hu_conv = ("new " + ty_info.java_hu_ty + "(null, ", ");\nret.ptrs_to.add(this)"), from_hu_conv = None)
                 else:
                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
                         ret_conv = ("long ret = (long)", ";"), ret_conv_name = "ret",
-                        arg_conv = None, arg_conv_name = None)
+                        arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
+                        to_hu_conv = ("TODO c", ""), from_hu_conv = None)
             else:
                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
-                    arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
+                    arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
+                    ret_conv = None, ret_conv_name = None,
+                    to_hu_conv = ("TODO d", ""), from_hu_conv = None)
 
     def map_fn(line, re_match, ret_arr_len, c_call_string):
         out_java.write("\t// " + line)
@@ -378,6 +443,7 @@ with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.arg
         out_c.write(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
 
         arg_names = []
+        default_constructor_args = {}
         takes_self = False
         args_known = not ret_info.passed_as_ptr or ret_info.rust_obj in opaque_structs or ret_info.rust_obj in trait_structs
         for idx, arg in enumerate(re_match.group(3).split(',')):
@@ -393,7 +459,23 @@ with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.arg
                 takes_self = True
             if arg_conv_info.passed_as_ptr and not arg_conv_info.rust_obj in opaque_structs:
                 if not arg_conv_info.rust_obj in trait_structs and not arg_conv_info.rust_obj in unitary_enums:
-                    print(re_match.group(2) + " bad - " + arg_conv_info.rust_obj)
+                    args_known = False
+            if arg_conv_info.arg_conv is not None and "Warning" in arg_conv_info.arg_conv:
+                if arg_conv_info.rust_obj in constructor_fns:
+                    assert not is_free
+                    for explode_arg in constructor_fns[arg_conv_info.rust_obj].split(','):
+                        explode_arg_conv = map_type(explode_arg, False, None, False)
+                        if explode_arg_conv.c_ty == "void":
+                            # We actually want to handle this case, but for now its only used in NetGraphMsgHandler::new()
+                            # which ends up resulting in a redundant constructor - both without arguments for the NetworkGraph.
+                            args_known = False
+                        assert explode_arg_conv.arg_name != "this_arg"
+                        if explode_arg_conv.passed_as_ptr and not explode_arg_conv.rust_obj in trait_structs:
+                            args_known = False
+                        if not arg_conv_info.arg_name in default_constructor_args:
+                            default_constructor_args[arg_conv_info.arg_name] = []
+                        default_constructor_args[arg_conv_info.arg_name].append(explode_arg_conv)
+                else:
                     args_known = False
             arg_names.append(arg_conv_info)
 
@@ -409,22 +491,21 @@ with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.arg
                 meth_n = re_match.group(2)[len(struct_meth) + 1:]
                 if ret_info.rust_obj == "LDK" + struct_meth:
                     out_java_struct.write(struct_meth + "(")
-                elif ret_info.rust_obj in opaque_structs or ret_info.rust_obj in trait_structs:
-                    out_java_struct.write(ret_info.rust_obj.replace("LDK", "") + " " + meth_n + "(")
                 else:
-                    out_java_struct.write(ret_info.java_ty + " " + meth_n + "(")
+                    out_java_struct.write(ret_info.java_hu_ty + " " + meth_n + "(")
                 for idx, arg in enumerate(arg_names):
                     if idx != 0:
                         if not takes_self or idx > 1:
                             out_java_struct.write(", ")
                     if arg.java_ty != "void" and arg.arg_name != "this_arg":
-                        if arg.passed_as_ptr:
-                            if arg.rust_obj in opaque_structs or arg.rust_obj in trait_structs:
-                                out_java_struct.write(arg.rust_obj.replace("LDK", "") + " " + arg.arg_name)
-                            else:
-                                out_java_struct.write(arg.rust_obj + " " + arg.arg_name)
+                        if arg.arg_name in default_constructor_args:
+                            for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
+                                if explode_idx != 0:
+                                    out_java_struct.write(", ")
+                                assert explode_arg.rust_obj in opaque_structs or explode_arg.rust_obj in trait_structs
+                                out_java_struct.write(explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
                         else:
-                            out_java_struct.write(arg.java_ty + " " + arg.arg_name)
+                            out_java_struct.write(arg.java_hu_ty + " " + arg.arg_name)
 
 
         out_java.write(");\n")
@@ -434,12 +515,14 @@ with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.arg
 
         for info in arg_names:
             if info.arg_conv is not None:
-                out_c.write("\t" + info.arg_conv.replace('\n', "\n\t") + "\n");
+                out_c.write("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
 
         if ret_info.ret_conv is not None:
-            out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'));
+            out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'))
+        elif ret_info.c_ty != "void":
+            out_c.write("\t" + ret_info.c_ty + " ret_val = ")
         else:
-            out_c.write("\treturn ");
+            out_c.write("\t")
 
         if c_call_string is None:
             out_c.write(re_match.group(2) + "(")
@@ -455,9 +538,15 @@ with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.arg
         out_c.write(")")
         if ret_info.ret_conv is not None:
             out_c.write(ret_conv_sfx.replace('\n', '\n\t'))
-            out_c.write("\n\treturn " + ret_info.ret_conv_name + ";")
         else:
             out_c.write(";")
+        for info in arg_names:
+            if info.arg_conv_cleanup is not None:
+                out_c.write("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
+        if ret_info.ret_conv is not None:
+            out_c.write("\n\treturn " + ret_info.ret_conv_name + ";")
+        elif ret_info.c_ty != "void":
+            out_c.write("\n\treturn ret_val;")
         out_c.write("\n}\n\n")
         if out_java_struct is not None:
             out_java_struct.write("\t\t")
@@ -466,36 +555,42 @@ with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.arg
             elif ret_info.java_ty != "void" and not ret_info.passed_as_ptr:
                 out_java_struct.write(ret_info.java_ty + " ret = ")
             elif ret_info.java_ty != "void":
-                out_java_struct.write(ret_info.rust_obj.replace("LDK", "") + " ret = ")
-                if ret_info.rust_obj in opaque_structs or ret_info.rust_obj in trait_structs:
-                    out_java_struct.write("new " + ret_info.rust_obj.replace("LDK", "") + "(null, ")
+                out_java_struct.write(ret_info.java_hu_ty + " ret = ")
+                if ret_info.to_hu_conv is not None:
+                    out_java_struct.write(ret_info.to_hu_conv[0])
             out_java_struct.write("bindings." + re_match.group(2) + "(")
             for idx, info in enumerate(arg_names):
                 if idx != 0:
                     out_java_struct.write(", ")
                 if info.arg_name == "this_arg":
                     out_java_struct.write("this.ptr")
-                elif info.passed_as_ptr and info.rust_obj in opaque_structs:
-                    out_java_struct.write(info.arg_name + ".ptr & ~1")
-                elif info.passed_as_ptr and info.rust_obj in trait_structs:
-                    out_java_struct.write(info.arg_name + ".ptr")
+                elif info.arg_name in default_constructor_args:
+                    out_java_struct.write("bindings." + info.java_hu_ty + "_new(")
+                    for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
+                        if explode_idx != 0:
+                            out_java_struct.write(", ")
+                        expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
+                        out_java_struct.write(explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
+                    out_java_struct.write(")")
+                elif info.from_hu_conv is not None:
+                    out_java_struct.write(info.from_hu_conv[0])
                 else:
                     out_java_struct.write(info.arg_name)
             out_java_struct.write(")")
-            if ret_info.rust_obj == "LDK" + struct_meth:
-                out_java_struct.write(");\n")
-            elif ret_info.rust_obj in opaque_structs:
-                out_java_struct.write(");\n")
-            elif ret_info.rust_obj in trait_structs:
-                out_java_struct.write(");\n\t\tret.ptrs_to.add(this);\n")
+            if ret_info.to_hu_conv is not None:
+                out_java_struct.write(ret_info.to_hu_conv[1].replace("\n", "\n\t\t") + ";\n")
             else:
                 out_java_struct.write(";\n")
 
             for info in arg_names:
                 if info.arg_name == "this_arg":
                     pass
-                elif info.passed_as_ptr and (info.rust_obj in opaque_structs or info.rust_obj in trait_structs):
-                    out_java_struct.write("\t\tthis.ptrs_to.add(" + info.arg_name + ");\n")
+                elif info.arg_name in default_constructor_args:
+                    for explode_arg in default_constructor_args[info.arg_name]:
+                        expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
+                        out_java_struct.write("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name, expl_arg_name) + ";\n")
+                elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
+                    out_java_struct.write("\t\t" + info.from_hu_conv[1] + ";\n")
 
             if ret_info.java_ty != "void" and ret_info.rust_obj != "LDK" + struct_meth:
                 out_java_struct.write("\t\treturn ret;\n")
@@ -785,6 +880,7 @@ with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.arg
                 elif fn_line.group(2) == "free":
                     out_c.write("\t\t.free = " + struct_name + "_JCalls_free,\n")
                 else:
+                    clone_fns.add(struct_name + "_clone")
                     out_c.write("\t\t.clone = " + struct_name + "_JCalls_clone,\n")
             for var_line in field_var_lines:
                 if var_line.group(1) in trait_structs:
@@ -821,7 +917,7 @@ with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.arg
             # For now, just disable enabling the _call_log - we don't know how to inverse-map String
             is_log = fn_line.group(2) == "log" and struct_name == "LDKLogger"
             if fn_line.group(2) != "free" and fn_line.group(2) != "clone" and fn_line.group(2) != "eq" and not is_log:
-                dummy_line = fn_line.group(1) + struct_name.replace("LDK", "") + "_call_" + fn_line.group(2) + " " + struct_name + "* this_arg" + fn_line.group(4) + "\n"
+                dummy_line = fn_line.group(1) + struct_name.replace("LDK", "") + "_" + fn_line.group(2) + " " + struct_name + "* this_arg" + fn_line.group(4) + "\n"
                 map_fn(dummy_line, re.compile("([A-Za-z_0-9]*) *([A-Za-z_0-9]*) *(.*)").match(dummy_line), None, "(this_arg_conv->" + fn_line.group(2) + ")(this_arg_conv->this_arg")
 
     out_c.write("""#include \"org_ldk_impl_bindings.h\"
@@ -1144,11 +1240,18 @@ class CommonBase {
                         out_java_struct.write("package org.ldk.structs;\n\n")
                         out_java_struct.write("import org.ldk.impl.bindings;\n")
                         out_java_struct.write("import org.ldk.enums.*;\n\n")
-                        out_java_struct.write("public class " + struct_name.replace("LDK","") + " extends CommonBase {\n")
+                        out_java_struct.write("public class " + struct_name.replace("LDK","") + " extends CommonBase")
+                        if struct_name.startswith("LDKLocked"):
+                            out_java_struct.write(" implements AutoCloseable")
+                        out_java_struct.write(" {\n")
                         out_java_struct.write("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); }\n")
-                        out_java_struct.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
-                        out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
-                        out_java_struct.write("\t\tbindings." + struct_name.replace("LDK","") + "_free(ptr); super.finalize();\n")
+                        if struct_name.startswith("LDKLocked"):
+                            out_java_struct.write("\t@Override public void close() {\n")
+                        else:
+                            out_java_struct.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
+                            out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
+                            out_java_struct.write("\t\tsuper.finalize();\n")
+                        out_java_struct.write("\t\tbindings." + struct_name.replace("LDK","") + "_free(ptr);\n")
                         out_java_struct.write("\t}\n\n")
                 elif result_contents is not None:
                     result_templ_structs.add(struct_name)
@@ -1183,6 +1286,7 @@ class CommonBase {
                                 out_c.write("\n\tret->" + e + " = " + ty_info.arg_conv_name + ";\n")
                             else:
                                 out_c.write("\tret->" + e + " = " + e + ";\n")
+                            assert ty_info.arg_conv_cleanup is None
                     out_c.write("\treturn (long)ret;\n")
                     out_c.write("}\n")
                 elif vec_ty is not None:
@@ -1222,6 +1326,7 @@ class CommonBase {
                             out_c.write("\t\t\t" + ty_info.c_ty + " arr_elem = java_elems[i];\n")
                             out_c.write("\t\t\t" + ty_info.arg_conv.replace("\n", "\n\t\t\t") + "\n")
                             out_c.write("\t\t\tret->data[i] = " + ty_info.arg_conv_name + ";\n")
+                            assert ty_info.arg_conv_cleanup is None
                         else:
                             out_c.write("\t\t\tret->data[i] = java_elems[i];\n")
                         out_c.write("\t\t}\n")
@@ -1265,27 +1370,36 @@ class CommonBase {
             elif line.startswith("typedef "):
                 alias_match =  struct_alias_regex.match(line)
                 if alias_match.group(1) in result_templ_structs:
+                    contents_ty = alias_match.group(1).replace("LDKCResultTempl", "LDKCResultPtr")
+                    res_ty, err_ty = result_ptr_struct_items[contents_ty]
+                    res_map = map_type(res_ty, True, None, False)
+                    err_map = map_type(err_ty, True, None, False)
+
                     out_java.write("\tpublic static native boolean " + alias_match.group(2) + "_result_ok(long arg);\n")
-                    out_java.write("\tpublic static native long " + alias_match.group(2) + "_get_inner(long arg);\n")
                     out_c.write("JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_" + alias_match.group(2).replace("_", "_1") + "_1result_1ok (JNIEnv * env, jclass _a, jlong arg) {\n")
                     out_c.write("\treturn ((" + alias_match.group(2) + "*)arg)->result_ok;\n")
                     out_c.write("}\n")
-                    out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + alias_match.group(2).replace("_", "_1") + "_1get_1inner (JNIEnv * env, jclass _a, jlong arg) {\n")
-                    contents_ty = alias_match.group(1).replace("LDKCResultTempl", "LDKCResultPtr")
-                    res_ty, err_ty = result_ptr_struct_items[contents_ty]
+
+                    out_java.write("\tpublic static native " + res_map.java_ty + " " + alias_match.group(2) + "_get_ok(long arg);\n")
+                    out_c.write("JNIEXPORT " + res_map.c_ty + " JNICALL Java_org_ldk_impl_bindings_" + alias_match.group(2).replace("_", "_1") + "_1get_1ok (JNIEnv * _env, jclass _a, jlong arg) {\n")
                     out_c.write("\t" + alias_match.group(2) + " *val = (" + alias_match.group(2) + "*)arg;\n")
-                    out_c.write("\tif (val->result_ok) {\n")
-                    if res_ty not in opaque_structs:
-                        out_c.write("\t\treturn (long)val->contents.result;\n")
+                    out_c.write("\tCHECK(val->result_ok);\n\t")
+                    if res_map.ret_conv is not None:
+                        out_c.write(res_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.result)")
+                        out_c.write(res_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + res_map.ret_conv_name)
                     else:
-                        out_c.write("\t\treturn (long)(val->contents.result->inner) | (val->contents.result->is_owned ? 1 : 0);\n")
-                    out_c.write("\t} else {\n")
-                    if err_ty not in opaque_structs:
-                        out_c.write("\t\treturn (long)val->contents.err;\n")
+                        out_c.write("return *val->contents.result")
+                    out_c.write(";\n}\n")
+
+                    out_java.write("\tpublic static native " + err_map.java_ty + " " + alias_match.group(2) + "_get_err(long arg);\n")
+                    out_c.write("JNIEXPORT " + err_map.c_ty + " JNICALL Java_org_ldk_impl_bindings_" + alias_match.group(2).replace("_", "_1") + "_1get_1err (JNIEnv * _env, jclass _a, jlong arg) {\n")
+                    out_c.write("\t" + alias_match.group(2) + " *val = (" + alias_match.group(2) + "*)arg;\n")
+                    out_c.write("\tCHECK(!val->result_ok);\n\t")
+                    if err_map.ret_conv is not None:
+                        out_c.write(err_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.err)")
+                        out_c.write(err_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + err_map.ret_conv_name)
                     else:
-                        out_c.write("\t\treturn (long)(val->contents.err->inner) | (val->contents.err->is_owned ? 1 : 0);\n")
-                    out_c.write("\t}\n}\n")
-                pass
+                        out_c.write("return *val->contents.err")
             elif fn_ptr is not None:
                 map_fn(line, fn_ptr, None, None)
             elif fn_ret_arr is not None: