1 from bindingstypes import *
8 def first_to_lower(string: str) -> str:
10 return first.lower() + string[1:]
12 def safe_arg_name(arg_name):
13 return "_" + arg_name if arg_name == "lock" or arg_name == "event" or arg_name == "params" else arg_name
15 def arg_name_repl(s, arg_name):
16 return s.replace(arg_name, "_" + arg_name) if arg_name == "lock" or arg_name == "event" or arg_name == "params" else s
19 def __init__(self, DEBUG: bool, target: Target, outdir: str, **kwargs):
22 self.c_array_class_caches = set()
23 self.function_ptr_counter = 0
24 self.function_ptrs = {}
25 self.c_type_map = dict(
26 bool = ['bool', 'long', 'bool[]'],
27 uint8_t = ['byte', 'long', 'byte[]'],
28 uint16_t = ['short', 'long', 'short[]'],
29 uint32_t = ['int', 'long', 'int[]'],
30 uint64_t = ['long', 'long', 'long[]'],
31 int64_t = ['long', 'long', 'long[]'],
32 double = ['double', 'long', 'double[]'],
34 self.java_type_map = dict(
37 self.java_hu_type_map = dict(
41 self.to_hu_conv_templates = dict(
42 ptr = '{human_type} {var_name}_hu_conv = null; if ({var_name} < 0 || {var_name} > 4096) { {var_name}_hu_conv = new {human_type}(null, {var_name}); }',
43 default = '{human_type} {var_name}_hu_conv = null; if ({var_name} < 0 || {var_name} > 4096) { {var_name}_hu_conv = new {human_type}(null, {var_name}); }'
46 self.bindings_header = """
50 using System.Collections.Generic;
51 using System.Runtime.InteropServices;
53 namespace org { namespace ldk { namespace impl {
55 internal class bindings {
56 static List<WeakReference> js_objs = new List<WeakReference>();
59 self.bindings_header += self.native_meth_decl("get_lib_version_string", "string") + "();\n"
60 self.bindings_header += self.native_meth_decl("get_ldk_c_bindings_version", "string") + "();\n"
61 self.bindings_header += self.native_meth_decl("get_ldk_version", "string") + "();\n\n"
62 self.bindings_header += self.native_meth_decl("allocate_buffer", "long") + "(long buflen);\n\n"
63 self.bindings_header += self.native_meth_decl("free_buffer", "void") + "(long buf);\n\n"
65 self.bindings_version_file = """
67 public class version {
68 public static string get_ldk_java_bindings_version() {
69 return "<git_version_ldk_garbagecollected>";
73 self.util_fn_pfx = """using org.ldk.impl;
76 using org.ldk.structs;
79 namespace org { namespace ldk { namespace util {
80 public class UtilMethods {
82 self.util_fn_sfx = "} } } }"
83 self.common_base = """using System.Collections.Generic;
84 using System.Diagnostics;
86 public class CommonBase {
87 protected internal long ptr;
88 protected internal LinkedList<object> ptrs_to = new LinkedList<object>();
89 protected CommonBase(long ptr) { Trace.Assert(ptr < 0 || ptr > 4096); this.ptr = ptr; }
93 self.txin_defn = """public class TxIn : CommonBase {
94 /** The witness in this input, in serialized form */
95 public readonly byte[] witness;
96 /** The script_sig in this input */
97 public readonly byte[] script_sig;
98 /** The transaction output's sequence number */
99 public readonly int sequence;
100 /** The txid this input is spending */
101 public readonly byte[] previous_txid;
102 /** The output index within the spent transaction of the output this input is spending */
103 public readonly int previous_vout;
105 internal TxIn(object _dummy, long ptr) : base(ptr) {
106 this.witness = InternalUtils.decodeUint8Array(bindings.TxIn_get_witness(ptr));
107 this.script_sig = InternalUtils.decodeUint8Array(bindings.TxIn_get_script_sig(ptr));
108 this.sequence = bindings.TxIn_get_sequence(ptr);
109 this.previous_txid = InternalUtils.decodeUint8Array(bindings.TxIn_get_previous_txid(ptr));
110 this.previous_vout = bindings.TxIn_get_previous_vout(ptr);
112 public TxIn(byte[] witness, byte[] script_sig, int sequence, byte[] previous_txid, int previous_vout)
113 : this(null, bindings.TxIn_new(InternalUtils.encodeUint8Array(witness), InternalUtils.encodeUint8Array(script_sig), sequence, InternalUtils.encodeUint8Array(previous_txid), previous_vout)) {}
116 if (ptr != 0) { bindings.TxIn_free(ptr); }
120 self.txout_defn = """public class TxOut : CommonBase {
121 /** The script_pubkey in this output */
122 public readonly byte[] script_pubkey;
123 /** The value, in satoshis, of this output */
124 public readonly long value;
126 internal TxOut(object _dummy, long ptr) : base(ptr) {
127 this.script_pubkey = InternalUtils.decodeUint8Array(bindings.TxOut_get_script_pubkey(ptr));
128 this.value = bindings.TxOut_get_value(ptr);
130 public TxOut(long value, byte[] script_pubkey) : this(null, bindings.TxOut_new(InternalUtils.encodeUint8Array(script_pubkey), value)) {}
133 if (ptr != 0) { bindings.TxOut_free(ptr); }
137 self.scalar_defn = """public class BigEndianScalar : CommonBase {
138 /** The bytes of the scalar value, in big endian */
139 public readonly byte[] scalar_bytes;
141 internal BigEndianScalar(object _dummy, long ptr) : base(ptr) {
142 this.scalar_bytes = InternalUtils.decodeUint8Array(bindings.BigEndianScalar_get_bytes(ptr));
144 public BigEndianScalar(byte[] scalar_bytes) : base(bindings.BigEndianScalar_new(InternalUtils.encodeUint8Array(scalar_bytes))) {
145 this.scalar_bytes = InternalUtils.decodeUint8Array(bindings.BigEndianScalar_get_bytes(ptr));
149 if (ptr != 0) { bindings.BigEndianScalar_free(ptr); }
154 self.c_file_pfx = """
155 // On OSX jlong (ie long long) is not equivalent to int64_t, so we override here
156 #define int64_t jlong
157 #include <lightning.h>
159 #include <stdatomic.h>
162 #define LIKELY(v) __builtin_expect(!!(v), 1)
163 #define UNLIKELY(v) __builtin_expect(!!(v), 0)
167 self.c_file_pfx = self.c_file_pfx + "#include <stdio.h>\n#define DEBUG_PRINT(...) fprintf(stderr, __VA_ARGS__)\n"
169 if not DEBUG or sys.platform == "darwin":
170 self.c_file_pfx = self.c_file_pfx + """#define do_MALLOC(a, _b, _c) malloc(a)
171 #define MALLOC(a, _) malloc(a)
172 #define FREE(p) if ((uint64_t)(p) > 4096) { free(p); }
173 #define CHECK_ACCESS(p)
174 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
177 self.c_file_pfx += """#define DO_ASSERT(a) (void)(a)
181 self.c_file_pfx = self.c_file_pfx + """#include <assert.h>
182 // Always run a, then assert it is true:
183 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
184 // Assert a is true or do nothing
185 #define CHECK(a) DO_ASSERT(a)
187 void __attribute__((constructor)) debug_log_version() {
188 if (check_get_ldk_version() == NULL)
189 DEBUG_PRINT("LDK version did not match the header we built against\\n");
190 if (check_get_ldk_bindings_version() == NULL)
191 DEBUG_PRINT("LDK C Bindings version did not match the header we built against\\n");
195 if sys.platform != "darwin":
196 self.c_file_pfx += """
197 // Running a leak check across all the allocations and frees of the JDK is a mess,
198 // so instead we implement our own naive leak checker here, relying on the -wrap
199 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
200 // and free'd in Rust or C across the generated bindings shared library.
204 self.c_file_pfx = self.c_file_pfx + "#include <execinfo.h>\n"
205 self.c_file_pfx = self.c_file_pfx + """
208 static pthread_mutex_t allocation_mtx;
210 void __attribute__((constructor)) init_mtx() {
211 DO_ASSERT(!pthread_mutex_init(&allocation_mtx, NULL));
215 typedef struct allocation {
216 struct allocation* next;
218 const char* struct_name;
221 unsigned long alloc_len;
223 static allocation* allocation_ll = NULL;
225 void* __real_malloc(size_t len);
226 void* __real_calloc(size_t nmemb, size_t len);
227 static void new_allocation(void* res, const char* struct_name, size_t len) {
228 allocation* new_alloc = __real_malloc(sizeof(allocation));
229 new_alloc->ptr = res;
230 new_alloc->struct_name = struct_name;
231 new_alloc->bt_len = backtrace(new_alloc->bt, BT_MAX);
232 new_alloc->alloc_len = len;
233 DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
234 new_alloc->next = allocation_ll;
235 allocation_ll = new_alloc;
236 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
238 static void* do_MALLOC(size_t len, const char* struct_name, int lineno) {
239 void* res = __real_malloc(len);
240 new_allocation(res, struct_name, lineno);
243 #define MALLOC(len, struct_name) do_MALLOC(len, struct_name, __LINE__)
245 void __real_free(void* ptr);
246 static void alloc_freed(void* ptr) {
247 allocation* p = NULL;
248 DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
249 allocation* it = allocation_ll;
250 while (it->ptr != ptr) {
251 p = it; it = it->next;
253 DEBUG_PRINT("ERROR: Tried to free unknown pointer %p at:\\n", ptr);
255 int bt_len = backtrace(bt, BT_MAX);
256 backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
257 DEBUG_PRINT("\\n\\n");
258 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
259 return; // addrsan should catch malloc-unknown and print more info than we have
262 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
263 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
264 DO_ASSERT(it->ptr == ptr);
267 static void FREE(void* ptr) {
268 if ((uint64_t)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
273 void* __wrap_malloc(size_t len) {
274 void* res = __real_malloc(len);
275 new_allocation(res, "malloc call", len);
278 void* __wrap_calloc(size_t nmemb, size_t len) {
279 void* res = __real_calloc(nmemb, len);
280 new_allocation(res, "calloc call", len);
283 void __wrap_free(void* ptr) {
284 if (ptr == NULL) return;
289 static void CHECK_ACCESS(const void* ptr) {
290 DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
291 allocation* it = allocation_ll;
292 while (it->ptr != ptr) {
295 DEBUG_PRINT("ERROR: Tried to access unknown pointer %p at:\\n", ptr);
297 int bt_len = backtrace(bt, BT_MAX);
298 backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
299 DEBUG_PRINT("\\n\\n");
300 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
301 return; // addrsan should catch and print more info than we have
304 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
306 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
307 if (v.is_owned && v.inner != NULL) { \\
308 const void *p = __unmangle_inner_ptr(v.inner); \\
314 void* __real_realloc(void* ptr, size_t newlen);
315 void* __wrap_realloc(void* ptr, size_t len) {
316 if (ptr != NULL) alloc_freed(ptr);
317 void* res = __real_realloc(ptr, len);
318 new_allocation(res, "realloc call", len);
321 void __wrap_reallocarray(void* ptr, size_t new_sz) {
322 // Rust doesn't seem to use reallocarray currently
326 void __attribute__((destructor)) check_leaks() {
327 unsigned long alloc_count = 0;
328 unsigned long alloc_size = 0;
329 DEBUG_PRINT("The following LDK-allocated blocks still remain.\\n");
330 DEBUG_PRINT("Note that this is only accurate if System.GC.Collect(); GC.WaitForPendingFinalizers();\\n");
331 DEBUG_PRINT("was called prior to exit after all LDK objects were out of scope.\\n");
332 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
333 DEBUG_PRINT("%s %p (%lu bytes) remains:\\n", a->struct_name, a->ptr, a->alloc_len);
334 backtrace_symbols_fd(a->bt, a->bt_len, STDERR_FILENO);
335 DEBUG_PRINT("\\n\\n");
337 alloc_size += a->alloc_len;
339 DEBUG_PRINT("%lu allocations remained for %lu bytes.\\n", alloc_count, alloc_size);
340 DEBUG_PRINT("Note that this is only accurate if System.GC.Collect(); GC.WaitForPendingFinalizers()\\n");
341 DEBUG_PRINT("was called prior to exit after all LDK objects were out of scope.\\n");
344 self.c_file_pfx = self.c_file_pfx + """
346 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
347 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
348 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
349 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
351 _Static_assert(sizeof(void*) <= 8, "Pointers must fit into 64 bits");
353 // Int types across Windows/Linux are different, so make sure we're using the right headers.
354 _Static_assert(sizeof(void*) == sizeof(uintptr_t), "stdints must be correct");
355 _Static_assert(sizeof(void*) == sizeof(intptr_t), "stdints must be correct");
356 _Static_assert(sizeof(uint64_t) == 8, "stdints must be correct");
357 _Static_assert(sizeof(int64_t) == 8, "stdints must be correct");
358 _Static_assert(sizeof(uint32_t) == 4, "stdints must be correct");
359 _Static_assert(sizeof(int32_t) == 4, "stdints must be correct");
360 _Static_assert(sizeof(uint16_t) == 2, "stdints must be correct");
361 _Static_assert(sizeof(int16_t) == 2, "stdints must be correct");
362 _Static_assert(sizeof(uint8_t) == 1, "stdints must be correct");
363 _Static_assert(sizeof(int8_t) == 1, "stdints must be correct");
365 #define DECL_ARR_TYPE(ty, name) \\
366 struct name##array { \\
367 uint64_t arr_len; /* uint32_t would suffice but we want to align uint64_ts as well */ \\
370 typedef struct name##array * name##Array; \\
371 static inline name##Array init_##name##Array(size_t arr_len, int lineno) { \\
372 name##Array arr = (name##Array)do_MALLOC(arr_len * sizeof(ty) + sizeof(uint64_t), #name" array init", lineno); \\
373 arr->arr_len = arr_len; \\
377 DECL_ARR_TYPE(int64_t, int64_t);
378 DECL_ARR_TYPE(uint64_t, uint64_t);
379 DECL_ARR_TYPE(int8_t, int8_t);
380 DECL_ARR_TYPE(int16_t, int16_t);
381 DECL_ARR_TYPE(uint32_t, uint32_t);
382 DECL_ARR_TYPE(void*, ptr);
383 DECL_ARR_TYPE(char, char);
384 typedef charArray jstring;
386 static inline jstring str_ref_to_cs(const char* chars, size_t len) {
387 charArray arr = init_charArray(len, __LINE__);
388 memcpy(arr->elems, chars, len);
391 static inline LDKStr str_ref_to_owned_c(const jstring str) {
392 char* newchars = MALLOC(str->arr_len + 1, "String chars");
393 memcpy(newchars, str->elems, str->arr_len);
394 newchars[str->arr_len] = 0;
398 .chars_is_owned = true
403 typedef bool jboolean;
405 int64_t CS_LDK_allocate_buffer(int64_t len) {
406 return (int64_t)MALLOC(len, "C#-requested buffer");
409 void CS_LDK_free_buffer(int64_t buf) {
413 jstring CS_LDK_get_ldk_c_bindings_version() {
414 return str_ref_to_cs(check_get_ldk_bindings_version(), strlen(check_get_ldk_bindings_version()));
416 jstring CS_LDK_get_ldk_version() {
417 return str_ref_to_cs(check_get_ldk_version(), strlen(check_get_ldk_version()));
421 self.c_version_file = """const char* CS_LDK_get_lib_version_string() {
422 return "<git_version_ldk_garbagecollected>";
425 self.hu_struct_file_prefix = """using org.ldk.impl;
430 namespace org { namespace ldk { namespace structs {
433 self.hu_struct_file_suffix = "} } }\n"
434 self.c_fn_args_pfx = ""
435 self.c_fn_ty_pfx = ""
436 self.file_ext = ".cs"
437 self.ptr_c_ty = "int64_t"
438 self.ptr_native_ty = "long"
439 self.u128_native_ty = "UInt128"
440 self.usize_c_ty = "int64_t"
441 self.usize_native_ty = "long"
442 self.native_zero_ptr = "0"
443 self.unitary_enum_c_ty = "int32_t"
444 self.ptr_arr = "ptrArray"
445 self.is_arr_some_check = ("", " != NULL")
446 self.get_native_arr_len_call = ("", "->arr_len")
448 self.bindings_footer_wip = "\tstatic bindings() {\n"
449 def bindings_footer(self):
452 def native_meth_decl(self, meth_name, ret_ty_str):
453 return "\t[DllImport (\"ldkcsharp\", EntryPoint=\"CS_LDK_" + meth_name + "\")] public static extern " + ret_ty_str + " " + meth_name
455 def c_fn_name_define_pfx(self, fn_name, have_args):
456 return " CS_LDK_" + fn_name + "("
458 def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
460 def create_native_arr_call(self, arr_len, ty_info):
461 if ty_info.c_ty == "ptrArray":
462 assert ty_info.rust_obj == "LDKCVec_U5Z" or (ty_info.subty is not None and (ty_info.subty.c_ty.endswith("Array") or ty_info.subty.rust_obj == "LDKStr"))
463 return "init_" + ty_info.c_ty + "(" + arr_len + ", __LINE__)"
464 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
465 if ty_info.c_ty == "int8_tArray":
466 return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
467 elif ty_info.c_ty == "int16_tArray":
468 return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + " * 2)")
471 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
472 if ty_info.c_ty == "int8_tArray" or ty_info.c_ty == "int16_tArray":
475 if ty_info.c_ty == "int16_tArray":
476 byte_len = arr_len + " * 2"
477 return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + byte_len + "); FREE(" + arr_name + ")"
479 if ty_info.c_ty == "ptrArray":
480 return "(void*) " + arr_name + "->elems"
482 return arr_name + "->elems"
483 def get_native_arr_elem(self, arr_name, idxc, ty_info):
484 assert False # Only called if above is None
485 def get_native_arr_ptr_call(self, ty_info):
486 if ty_info.subty is not None:
487 return "(" + ty_info.subty.c_ty + "*)(((uint8_t*)", ") + 8)"
488 return "(" + ty_info.c_ty + "*)(((uint8_t*)", ") + 8)"
489 def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
491 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
492 if ty_info.c_ty == "int8_tArray":
493 return "FREE(" + arr_name + ");"
495 return "FREE(" + arr_name + ")"
497 def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty, is_nullable):
498 if elem_ty.java_hu_ty == "UInt5":
499 return "InternalUtils.convUInt5Array(" + arr_name + ")"
500 elif elem_ty.java_hu_ty == "WitnessVersion":
501 return "InternalUtils.convWitnessVersionArray(" + arr_name + ")"
503 return "InternalUtils.mapArray(" + arr_name + ", " + conv_name + " => " + elem_ty.from_hu_conv[0] + ")"
505 def str_ref_to_native_call(self, var_name, str_len):
506 return "str_ref_to_cs(" + var_name + ", " + str_len + ")"
507 def str_ref_to_c_call(self, var_name):
508 return "str_ref_to_owned_c(" + var_name + ")"
509 def str_to_hu_conv(self, var_name):
510 return "string " + var_name + "_conv = InternalUtils.decodeString(" + var_name + ");"
511 def str_from_hu_conv(self, var_name):
512 return ("InternalUtils.encodeString(" + var_name + ")", "")
516 for fn_suffix in self.function_ptrs:
517 cret = self.function_ptrs[fn_suffix]["ret"][1]
518 cargs = self.function_ptrs[fn_suffix]["args"][1]
520 typedef {cret} (*invoker_{fn_suffix})(int obj_ptr, int fn_id{cargs});
521 static invoker_{fn_suffix} js_invoke_function_{fn_suffix};
522 int CS_LDK_register_{fn_suffix}_invoker(invoker_{fn_suffix} invoker) {{
523 js_invoke_function_{fn_suffix} = invoker;
530 def var_decl_statement(self, ty_string, var_name, statement):
531 return ty_string + " " + var_name + " = " + statement
533 def get_java_arr_len(self, arr_name):
534 return "InternalUtils.getArrayLength(" + arr_name + ")"
536 def get_java_arr_elem(self, elem_ty, arr_name, idx):
537 if elem_ty.c_ty == "int64_t" or elem_ty.c_ty == "uint64_t" or elem_ty.c_ty.endswith("Array") or elem_ty.c_ty == "uintptr_t":
538 return "InternalUtils.getU64ArrayElem(" + arr_name + ", " + idx + ")"
539 elif elem_ty.rust_obj == "LDKU5":
540 return "InternalUtils.getU8ArrayElem(" + arr_name + ", " + idx + ")"
541 elif elem_ty.rust_obj == "LDKStr":
542 return "InternalUtils.getU32ArrayElem(" + arr_name + ", " + idx + ")"
546 def constr_hu_array(self, ty_info, arr_len):
547 base_ty = ty_info.subty.java_hu_ty.split("[")[0].split("<")[0]
548 conv = "new " + base_ty + "[" + arr_len + "]"
549 if "[" in ty_info.subty.java_hu_ty.split("<")[0]:
550 # Do a bit of a dance to move any excess [] to the end
551 conv += "[" + ty_info.subty.java_hu_ty.split("<")[0].split("[")[1]
553 def cleanup_converted_native_array(self, ty_info, arr_name):
554 return "bindings.free_buffer(" + arr_name + ");"
556 def primitive_arr_from_hu(self, arr_ty, fixed_len, arr_name):
557 mapped_ty = arr_ty.subty
559 if arr_ty.rust_obj == "LDKU128":
560 return ("InternalUtils.encodeUint8Array(" + arr_name + ".getLEBytes())", "")
561 if fixed_len is not None:
562 inner = "InternalUtils.check_arr_len(" + arr_name + ", " + fixed_len + ")"
563 if mapped_ty.c_ty.endswith("Array"):
564 return ("InternalUtils.encodeUint64Array(" + inner + ")", "")
565 elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
566 return ("InternalUtils.encodeUint8Array(" + inner + ")", "")
567 elif mapped_ty.c_ty == "uint16_t" or mapped_ty.c_ty == "int16_t":
568 return ("InternalUtils.encodeUint16Array(" + inner + ")", "")
569 elif mapped_ty.c_ty == "uint32_t":
570 return ("InternalUtils.encodeUint32Array(" + inner + ")", "")
571 elif mapped_ty.c_ty == "int64_t" or mapped_ty.c_ty == "uint64_t" or mapped_ty.rust_obj == "LDKStr":
572 return ("InternalUtils.encodeUint64Array(" + inner + ")", "")
574 print(mapped_ty.c_ty)
577 def primitive_arr_to_hu(self, arr_ty, fixed_len, arr_name, conv_name):
578 mapped_ty = arr_ty.subty
579 if arr_ty.rust_obj == "LDKU128":
580 return "org.ldk.util.UInt128 " + conv_name + " = new org.ldk.util.UInt128(" + arr_name + ");"
581 elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
582 return "byte[] " + conv_name + " = InternalUtils.decodeUint8Array(" + arr_name + ");"
583 elif mapped_ty.c_ty == "uint16_t" or mapped_ty.c_ty == "int16_t":
584 return "short[] " + conv_name + " = InternalUtils.decodeUint16Array(" + arr_name + ");"
585 elif mapped_ty.c_ty == "uint64_t" or mapped_ty.c_ty == "int64_t":
586 return "long[] " + conv_name + " = InternalUtils.decodeUint64Array(" + arr_name + ");"
590 def java_arr_ty_str(self, elem_ty_str):
593 def for_n_in_range(self, n, minimum, maximum):
594 return "for (int " + n + " = " + minimum + "; " + n + " < " + maximum + "; " + n + "++) {"
595 def for_n_in_arr(self, n, arr_name, arr_elem_ty):
596 return ("foreach (" + arr_elem_ty.java_hu_ty + " " + n + " in " + arr_name + ") { ", " }")
598 def get_ptr(self, var):
600 def set_null_skip_free(self, var):
601 return var + ".ptr" + " = 0;"
603 def add_ref(self, holder, referent):
604 return "if (" + holder + " != null) { " + holder + ".ptrs_to.AddLast(" + referent + "); }"
606 def fully_qualified_hu_ty_path(self, ty):
607 if ty.java_fn_ty_arg.startswith("L") and ty.java_fn_ty_arg.endswith(";"):
609 if ty.java_hu_ty == "UnqualifiedError" or ty.java_hu_ty == "UInt128" or ty.java_hu_ty == "UInt5" or ty.java_hu_ty == "WitnessVersion":
610 return "org.ldk.util." + ty.java_hu_ty
611 if not ty.is_native_primitive and ty.rust_obj is not None and not "[]" in ty.java_hu_ty:
612 return "org.ldk.structs." + ty.java_hu_ty
615 def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
616 out_java_enum = "namespace org { namespace ldk { namespace enums {"
620 out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_cs(int32_t ord) {\n"
621 out_c += "\tswitch (ord) {\n"
623 if enum_doc_comment is not None:
624 out_java_enum += "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
625 out_java_enum += "public enum " + struct_name + " {\n"
627 for var, var_docs in variants:
628 if var_docs is not None:
629 out_java_enum += "\t/**\n\t * " + var_docs.replace("\n", "\n\t * ") + "\n\t */\n"
630 out_java_enum += "\t" + var + ",\n"
631 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
634 out_c += "\t\tdefault: abort();\n"
638 out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_cs(LDK" + struct_name + " val) {\n"
639 out_c = out_c + "\tswitch (val) {\n"
641 for var, _ in variants:
642 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
644 out_c = out_c + "\t\tdefault: abort();\n"
645 out_c = out_c + "\t}\n"
646 out_c = out_c + "}\n"
648 return (out_c, out_java_enum + "} } }\n", out_java)
650 def c_unitary_enum_to_native_call(self, ty_info):
651 return (ty_info.rust_obj + "_to_cs(", ")")
652 def native_unitary_enum_to_c_call(self, ty_info):
653 return (ty_info.rust_obj + "_from_cs(", ")")
655 def c_complex_enum_pfx(self, struct_name, variants, init_meth_jty_strs):
658 out_c = out_c + "static jclass " + struct_name + "_" + var + "_class = NULL;\n"
659 out_c = out_c + "static jmethodID " + struct_name + "_" + var + "_meth = NULL;\n"
660 out_c += "void" + self.c_fn_name_define_pfx(struct_name.replace("_", "_1") + "_init", True) + self.c_fn_args_pfx + ") {\n"
661 for var_name in variants:
662 out_c += "\t" + struct_name + "_" + var_name + "_class =\n"
663 out_c += "\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"org/ldk/impl/bindings$" + struct_name + "$" + var_name + "\"));\n"
664 out_c += "\tCHECK(" + struct_name + "_" + var_name + "_class != NULL);\n"
665 out_c += "\t" + struct_name + "_" + var_name + "_meth = (*env)->GetMethodID(env, " + struct_name + "_" + var_name + "_class, \"<init>\", \"(" + init_meth_jty_strs[var_name] + ")V\");\n"
666 out_c += "\tCHECK(" + struct_name + "_" + var_name + "_meth != NULL);\n"
667 out_c = out_c + "}\n"
670 def c_complex_enum_pass_ty(self, struct_name):
673 def c_constr_native_complex_enum(self, struct_name, variant, c_params):
674 ret = "(*env)->NewObject(env, " + struct_name + "_" + variant + "_class, " + struct_name + "_" + variant + "_meth"
675 for param in c_params:
676 ret = ret + ", " + param
679 def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
680 out_typescript_bindings = ""
681 super_instantiator = ""
682 bindings_instantiator = ""
683 pointer_to_adder = ""
684 impl_constructor_arguments = ""
685 for var in flattened_field_var_conversions:
686 if isinstance(var, ConvInfo):
687 impl_constructor_arguments += f", {var.java_hu_ty} {var.arg_name}"
688 if var.from_hu_conv is not None:
689 bindings_instantiator += ", " + var.from_hu_conv[0]
690 if var.from_hu_conv[1] != "":
691 pointer_to_adder += "\t\t\t" + var.from_hu_conv[1] + ";\n"
693 bindings_instantiator += ", " + first_to_lower(var.arg_name)
695 bindings_instantiator += ", " + first_to_lower(var[1]) + ".instance_idx"
696 pointer_to_adder += "\t\timpl_holder.held.ptrs_to.AddLast(" + first_to_lower(var[1]) + ");\n"
697 impl_constructor_arguments += f", {var[0].replace('LDK', '')}Interface {first_to_lower(var[1])}_impl"
699 super_constructor_statements = ""
700 trait_constructor_arguments = ""
701 for var in field_var_conversions:
702 if isinstance(var, ConvInfo):
703 trait_constructor_arguments += ", " + var.arg_name
705 super_constructor_statements += "\t\t" + var[1] + " " + first_to_lower(var[1]) + " = " + var[1] + ".new_impl(" + first_to_lower(var[1]) + "_impl"
706 super_instantiator = ""
707 for suparg in var[2]:
708 if isinstance(suparg, ConvInfo):
709 super_instantiator += ", " + suparg.arg_name
711 super_instantiator += ", " + first_to_lower(suparg[1]) + "_impl"
712 super_constructor_statements += super_instantiator + ");\n"
713 trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".instance_idx"
714 for suparg in var[2]:
715 if isinstance(suparg, ConvInfo):
716 trait_constructor_arguments += ", " + suparg.arg_name
718 # Blindly assume that we can just strip the first arg to build the args for the supertrait
719 super_constructor_statements += "\t\t" + suparg[1] + " " + first_to_lower(suparg[1]) + " = " + suparg[1] + ".new_impl(" + super_instantiator.split(", ", 1)[1] + ");\n"
720 trait_constructor_arguments += ", " + suparg[1]
722 # BUILD INTERFACE METHODS
724 java_trait_wrapper = "\tprivate class " + struct_name + "Holder { internal " + struct_name.replace("LDK", "") + " held; }\n"
725 java_trait_wrapper += "\tprivate class " + struct_name + "Impl : bindings." + struct_name + " {\n"
726 java_trait_wrapper += "\t\tinternal " + struct_name + "Impl(" + struct_name.replace("LDK", "") + "Interface arg, " + struct_name + "Holder impl_holder) { this.arg = arg; this.impl_holder = impl_holder; }\n"
727 java_trait_wrapper += "\t\tprivate " + struct_name.replace("LDK", "") + "Interface arg;\n"
728 java_trait_wrapper += "\t\tprivate " + struct_name + "Holder impl_holder;\n"
730 for fn_line in field_function_lines:
731 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
732 fn_name = fn_line.fn_name
733 if fn_name == "lock": # reserved symbol
735 java_trait_wrapper += "\t\tpublic " + fn_line.ret_ty_info.java_ty + " " + fn_name + "("
737 for idx, arg_conv_info in enumerate(fn_line.args_ty):
739 java_trait_wrapper += ", "
740 java_trait_wrapper += arg_conv_info.java_ty + " _" + arg_conv_info.arg_name
742 java_trait_wrapper += ") {\n"
744 for arg_info in fn_line.args_ty:
745 if arg_info.to_hu_conv is not None:
746 java_trait_wrapper += "\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t").replace(arg_info.arg_name, "_" + arg_info.arg_name) + "\n"
748 if fn_line.ret_ty_info.java_ty != "void":
749 java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_name + "("
751 java_trait_wrapper += "\t\t\targ." + fn_name + "("
753 for idx, arg_info in enumerate(fn_line.args_ty):
755 java_trait_wrapper += ", "
756 if arg_info.to_hu_conv_name is not None:
757 java_trait_wrapper += arg_info.to_hu_conv_name.replace(arg_info.arg_name, "_" + arg_info.arg_name)
759 java_trait_wrapper += "_" + arg_info.arg_name
761 java_trait_wrapper += ");\n"
762 java_trait_wrapper += "\t\t\t\tGC.KeepAlive(arg);\n"
763 if fn_line.ret_ty_info.java_ty != "void":
764 if fn_line.ret_ty_info.from_hu_conv is not None:
765 java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.java_ty + " result = " + fn_line.ret_ty_info.from_hu_conv[0] + ";\n"
766 if fn_line.ret_ty_info.from_hu_conv[1] != "":
767 java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held") + ";\n"
768 java_trait_wrapper += "\t\t\treturn result;\n"
770 java_trait_wrapper += "\t\t\treturn ret;\n"
771 java_trait_wrapper += "\t\t}\n"
772 java_trait_wrapper += "\t}"
774 out_java_interface = ""
776 for fn_line in field_function_lines:
777 java_method_descriptor = ""
778 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
779 out_java_interface += "\t/**" + fn_line.docs.replace("\n", "\n\t * ") + "\n\t */\n"
780 out_java_interface += "\t" + fn_line.ret_ty_info.java_hu_ty + " " + fn_line.fn_name + "("
782 for idx, arg_conv_info in enumerate(fn_line.args_ty):
784 out_java_interface += ", "
785 out_java_interface += f"{arg_conv_info.java_hu_ty} {safe_arg_name(arg_conv_info.arg_name)}"
786 java_method_descriptor += arg_conv_info.java_fn_ty_arg
787 out_java_interface += f");\n"
788 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
789 java_methods.append((fn_line.fn_name, java_method_descriptor))
791 formatted_trait_docs = trait_doc_comment.replace("\n", "\n * ")
792 out_typescript_human = f"""
793 {self.hu_struct_file_prefix}
795 /** An implementation of {struct_name.replace("LDK","")} */
796 public interface {struct_name.replace("LDK", "")}Interface {{
797 {out_java_interface}}}
800 * {formatted_trait_docs}
802 public class {struct_name.replace("LDK","")} : CommonBase {{
803 internal bindings.{struct_name} bindings_instance;
804 internal long instance_idx;
806 internal {struct_name.replace("LDK","")}(object _dummy, long ptr) : base(ptr) {{ bindings_instance = null; }}
807 ~{struct_name.replace("LDK","")}() {{
808 if (ptr != 0) {{ bindings.{struct_name.replace("LDK","")}_free(ptr); }}
813 /** Creates a new instance of {struct_name.replace("LDK","")} from a given implementation */
814 public static {struct_name.replace("LDK", "")} new_impl({struct_name.replace("LDK", "")}Interface arg{impl_constructor_arguments}) {{
815 {struct_name}Holder impl_holder = new {struct_name}Holder();
816 {struct_name}Impl impl = new {struct_name}Impl(arg, impl_holder);
817 {super_constructor_statements} long[] ptr_idx = bindings.{struct_name}_new(impl{bindings_instantiator});
819 impl_holder.held = new {struct_name.replace("LDK", "")}(null, ptr_idx[0]);
820 impl_holder.held.instance_idx = ptr_idx[1];
821 impl_holder.held.bindings_instance = impl;
822 {pointer_to_adder} return impl_holder.held;
827 out_typescript_bindings += "\tpublic interface " + struct_name + " {\n"
829 for fn_line in field_function_lines:
830 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
831 out_typescript_bindings += f"\t\t{fn_line.ret_ty_info.java_ty} {fn_line.fn_name}("
833 for idx, arg_conv_info in enumerate(fn_line.args_ty):
835 out_typescript_bindings = out_typescript_bindings + ", "
836 out_typescript_bindings += f"{arg_conv_info.java_ty} {safe_arg_name(arg_conv_info.arg_name)}"
838 out_typescript_bindings += f");\n"
840 out_typescript_bindings += "\t}\n"
842 c_call_extra_args = ""
843 native_fn_args = "long impl_idx"
844 for var in flattened_field_var_conversions:
845 if isinstance(var, ConvInfo):
846 native_fn_args += ", " + var.java_ty + " " + var.arg_name
848 native_fn_args += ", long " + var[1]
849 out_typescript_bindings += self.native_meth_decl(struct_name + "_new", "long") + "_native(" + native_fn_args + ");\n"
850 out_typescript_bindings += f"\tpublic static long[] {struct_name}_new({struct_name} impl"
851 for var in flattened_field_var_conversions:
852 if isinstance(var, ConvInfo):
853 out_typescript_bindings += f", {var.java_ty} {var.arg_name}"
854 c_call_extra_args += f", {var.arg_name}"
856 out_typescript_bindings += f", long {var[1]}"
857 c_call_extra_args += f", {var[1]}"
860 out_typescript_bindings += f""") {{
861 long new_obj_idx = js_objs.Count;
863 for (; i < js_objs.Count; i++) {{
864 if (js_objs[i] == null || !js_objs[i].IsAlive) {{ new_obj_idx = i; break; }}
866 if (i == js_objs.Count) {{
867 js_objs.Add(new WeakReference(impl));
869 js_objs[i] = new WeakReference(impl);
871 long[] ret = new long[2];
872 ret[0] = {struct_name}_new_native(i{c_call_extra_args});
878 # Now that we've written out our java code (and created java_meths), generate C
879 out_c = "typedef struct " + struct_name + "_JCalls {\n"
880 out_c += "\tatomic_size_t refcnt;\n"
881 out_c += "\tuint32_t instance_ptr;\n"
882 for var in flattened_field_var_conversions:
883 if isinstance(var, ConvInfo):
884 # We're a regular ol' field
888 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
889 out_c = out_c + "} " + struct_name + "_JCalls;\n"
891 for fn_line in field_function_lines:
892 if fn_line.fn_name == "free":
893 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
894 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
895 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
896 out_c = out_c + "\t\tFREE(j_calls);\n"
897 out_c = out_c + "\t}\n}\n"
899 for idx, fn_line in enumerate(field_function_lines):
900 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
901 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
902 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
903 if fn_line.self_is_const:
904 out_c = out_c + "const void* this_arg"
906 out_c = out_c + "void* this_arg"
908 for idx, arg in enumerate(fn_line.args_ty):
909 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
911 out_c = out_c + ") {\n"
912 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
914 for arg_info in fn_line.args_ty:
915 if arg_info.ret_conv is not None:
916 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
917 out_c = out_c + arg_info.arg_name
918 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
920 ty_to_c = lambda jty, ty: "b" if jty == "bool" else "c" if jty == "char" else "s" if jty == "short" else "i" if jty == "int" else "l" if jty == "long" else "void" if jty == "void" else jty
922 fn_java_callback_args = ""
923 fn_c_callback_args = ""
924 fn_callback_call_args = ""
925 fn_suffix = ty_to_c(fn_line.ret_ty_info.java_ty, fn_line.ret_ty_info) + "_"
927 for arg_info in fn_line.args_ty:
928 fn_suffix += ty_to_c(arg_info.java_ty, arg_info)
929 fn_java_callback_args += ", " + arg_info.java_ty + " " + chr(ord("a") + idx)
930 if arg_info.c_ty.endswith("Array") or arg_info.c_ty == "jstring":
931 fn_c_callback_args += ", int64_t " + chr(ord("a") + idx)
933 fn_c_callback_args += ", " + arg_info.c_ty + " " + chr(ord("a") + idx)
935 fn_callback_call_args += ", "
936 fn_callback_call_args += chr(ord("a") + idx)
938 if fn_line.ret_ty_info.c_ty.endswith("Array"):
939 out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (" + fn_line.ret_ty_info.c_ty + ")"
940 out_c += "js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
941 elif fn_line.ret_ty_info.java_ty == "void":
942 out_c = out_c + "\tjs_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
943 elif fn_line.ret_ty_info.java_hu_ty == "string":
944 out_c += "\tjstring ret = (jstring)js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
945 elif fn_line.ret_ty_info.arg_conv is None:
946 out_c += "\treturn js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
948 out_c += "\tuint64_t ret = js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
950 if fn_suffix not in self.function_ptrs:
951 caller_ret_c_ty = fn_line.ret_ty_info.c_ty
952 if fn_line.ret_ty_info.c_ty.endswith("Array") or fn_line.ret_ty_info.c_ty == "jstring":
953 caller_ret_c_ty = "int64_t"
954 self.function_ptrs[fn_suffix] = {"args": [fn_java_callback_args, fn_c_callback_args], "ret": [fn_line.ret_ty_info.java_ty, caller_ret_c_ty]}
955 self.function_ptrs[fn_suffix][self.function_ptr_counter] = (struct_name, fn_line.fn_name, fn_callback_call_args)
956 self.function_ptr_counter += 1
958 for idx, arg_info in enumerate(fn_line.args_ty):
959 if arg_info.ret_conv is not None:
960 if arg_info.c_ty.endswith("Array") or arg_info.c_ty == "jstring":
961 out_c += ", (int64_t)" + arg_info.ret_conv_name
963 out_c += ", " + arg_info.ret_conv_name
965 assert False # TODO: Would we need some conversion here?
966 out_c += ", (int64_t)" + arg_info.arg_name
967 out_c = out_c + ");\n"
968 if fn_line.ret_ty_info.arg_conv is not None:
969 out_c = out_c + "\t" + fn_line.ret_ty_info.arg_conv.replace("\n", "\n\t") + "\n\treturn " + fn_line.ret_ty_info.arg_conv_name + ";\n"
971 out_c = out_c + "}\n"
973 # Write out a clone function whether we need one or not, as we use them in moving to rust
974 out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
975 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
976 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
977 for var in flattened_field_var_conversions:
978 if not isinstance(var, ConvInfo):
979 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[2].replace(".", "->") + "->refcnt, 1, memory_order_release);\n"
980 out_c = out_c + "}\n"
982 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (int64_t o"
983 for var in flattened_field_var_conversions:
984 if isinstance(var, ConvInfo):
985 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
987 out_c = out_c + ", int64_t " + var[1]
988 out_c = out_c + ") {\n"
990 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
991 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
992 out_c = out_c + "\tcalls->instance_ptr = o;\n"
994 for (fn_name, java_meth_descr) in java_meths:
995 if fn_name != "free" and fn_name != "cloned":
996 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
997 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
999 for var in flattened_field_var_conversions:
1000 if isinstance(var, ConvInfo) and var.arg_conv is not None:
1001 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
1002 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
1003 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
1004 for fn_line in field_function_lines:
1005 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1006 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
1007 elif fn_line.fn_name == "free":
1008 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
1010 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
1011 for var in field_var_conversions:
1012 if isinstance(var, ConvInfo):
1013 if var.arg_conv_name is not None:
1014 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
1015 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
1017 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
1018 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
1020 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
1021 for suparg in var[2]:
1022 if isinstance(suparg, ConvInfo):
1023 out_c += ", " + suparg.arg_name
1025 out_c += ", " + suparg[1]
1027 out_c = out_c + "\t};\n"
1028 for var in flattened_field_var_conversions:
1029 if not isinstance(var, ConvInfo):
1030 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[2] + ".this_arg;\n"
1031 out_c = out_c + "\treturn ret;\n"
1032 out_c = out_c + "}\n"
1034 out_c = out_c + self.c_fn_ty_pfx + "uint64_t " + self.c_fn_name_define_pfx(struct_name + "_new", True) + "int32_t o"
1035 for var in flattened_field_var_conversions:
1036 if isinstance(var, ConvInfo):
1037 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1039 out_c = out_c + ", int32_t " + var[1]
1040 out_c = out_c + ") {\n"
1041 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
1042 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
1043 for var in flattened_field_var_conversions:
1044 if isinstance(var, ConvInfo):
1045 out_c = out_c + ", " + var.arg_name
1047 out_c = out_c + ", " + var[1]
1048 out_c = out_c + ");\n"
1049 out_c = out_c + "\treturn tag_ptr(res_ptr, true);\n"
1050 out_c = out_c + "}\n"
1052 return (out_typescript_bindings, out_typescript_human, out_c)
1054 def trait_struct_inc_refcnt(self, ty_info):
1055 base_conv = "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
1056 base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
1057 base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_cloned(&" + ty_info.var_name + "_conv);\n}"
1060 def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
1061 bindings_type = struct_name.replace("LDK", "")
1062 java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
1068 out_java_enum += (self.hu_struct_file_prefix)
1070 java_hu_class = "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
1071 java_hu_class += "public class " + java_hu_type + " : CommonBase {\n"
1072 java_hu_class += f"\tprotected {java_hu_type}(object _dummy, long ptr) : base(ptr)" + " { }\n"
1073 java_hu_class += "\t~" + java_hu_type + "() {\n"
1074 java_hu_class += "\t\tif (ptr != 0) { bindings." + bindings_type + "_free(ptr); }\n"
1075 java_hu_class += "\t}\n\n"
1076 java_hu_class += f"\tinternal static {java_hu_type} constr_from_ptr(long ptr) {{\n"
1077 java_hu_class += f"\t\tlong raw_ty = bindings." + struct_name + "_ty_from_ptr(ptr);\n"
1078 out_c += self.c_fn_ty_pfx + "uint32_t" + self.c_fn_name_define_pfx(struct_name + "_ty_from_ptr", True) + self.ptr_c_ty + " ptr) {\n"
1079 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
1080 out_c += "\tswitch(obj->tag) {\n"
1081 java_hu_class += "\t\tswitch (raw_ty) {\n"
1082 java_hu_subclasses = ""
1085 for var in variant_list:
1086 java_hu_subclasses += "\t/** A " + java_hu_type + " of type " + var.var_name + " */\n"
1087 java_hu_subclasses += "\tpublic class " + java_hu_type + "_" + var.var_name + " : " + java_hu_type + " {\n"
1088 java_hu_class += f"\t\t\tcase {var_idx}: "
1089 java_hu_class += "return new " + java_hu_type + "_" + var.var_name + "(ptr);\n"
1090 out_c += f"\t\tcase {struct_name}_{var.var_name}: return {var_idx};\n"
1092 for idx, (field_ty, field_docs) in enumerate(var.fields):
1093 if field_docs is not None:
1094 java_hu_subclasses += "\t\t/**\n\t\t * " + field_docs.replace("\n", "\n\t\t * ") + "\n\t\t */\n"
1095 java_hu_subclasses += f"\t\tpublic {field_ty.java_hu_ty} {field_ty.arg_name};\n"
1096 if field_ty.to_hu_conv is not None:
1097 hu_conv_body += f"\t\t\t{field_ty.java_ty} {field_ty.arg_name} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1098 hu_conv_body += f"\t\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1099 hu_conv_body += f"\t\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1101 hu_conv_body += f"\t\t\tthis.{field_ty.arg_name} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1102 java_hu_subclasses += "\t\tinternal " + java_hu_type + "_" + var.var_name + "(long ptr) : base(null, ptr) {\n"
1103 java_hu_subclasses += hu_conv_body
1104 java_hu_subclasses += "\t\t}\n\t}\n"
1106 java_hu_class += "\t\t\tdefault:\n\t\t\t\tthrow new ArgumentException(\"Impossible enum variant\");\n\t\t}\n\t}\n\n"
1107 out_java += self.native_meth_decl(struct_name + "_ty_from_ptr", "long") + "(long ptr);\n"
1108 out_c += ("\t\tdefault: abort();\n")
1109 out_c += ("\t}\n}\n")
1111 for var in variant_list:
1112 for idx, (field_map, _) in enumerate(var.fields):
1113 fn_name = f"{struct_name}_{var.var_name}_get_{field_map.arg_name}"
1114 out_c += self.c_fn_ty_pfx + field_map.c_ty + self.c_fn_name_define_pfx(fn_name, True) + self.ptr_c_ty + " ptr) {\n"
1115 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
1116 out_c += f"\tCHECK(obj->tag == {struct_name}_{var.var_name});\n"
1117 if field_map.ret_conv is not None:
1118 out_c += ("\t" + field_map.ret_conv[0].replace("\n", "\n\t"))
1119 if var.tuple_variant:
1120 out_c += "obj->" + camel_to_snake(var.var_name)
1122 out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
1123 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1124 out_c += "\treturn " + field_map.ret_conv_name + ";\n"
1126 if var.tuple_variant:
1127 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + ";\n"
1129 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name + ";\n"
1131 out_java += self.native_meth_decl(fn_name, field_map.java_ty) + "(long ptr);\n"
1132 out_java_enum += java_hu_class
1133 out_java_enum += java_hu_subclasses
1134 return (out_java, out_java_enum, out_c)
1136 def map_opaque_struct(self, struct_name, struct_doc_comment):
1137 out_opaque_struct_human = ""
1138 out_opaque_struct_human += self.hu_struct_file_prefix
1139 out_opaque_struct_human += "\n/**\n * " + struct_doc_comment.replace("\n", "\n * ") + "\n */\n"
1140 hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
1141 out_opaque_struct_human += ("public class " + hu_name + " : CommonBase")
1142 if struct_name.startswith("LDKLocked") or struct_name.startswith("LDKReadOnly"):
1143 out_opaque_struct_human += (", IDisposable")
1144 out_opaque_struct_human += (" {\n")
1145 out_opaque_struct_human += ("\tinternal " + hu_name + "(object _dummy, long ptr) : base(ptr) { }\n")
1146 if struct_name.startswith("LDKLocked") or struct_name.startswith("LDKReadOnly"):
1147 out_opaque_struct_human += ("\tpublic void Dispose() {\n")
1149 out_opaque_struct_human += ("\t~" + hu_name + "() {\n")
1150 out_opaque_struct_human += ("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n")
1151 out_opaque_struct_human += ("\t}\n\n")
1152 return out_opaque_struct_human
1154 def map_tuple(self, struct_name):
1155 return self.map_opaque_struct(struct_name, "A Tuple")
1157 def map_result(self, struct_name, res_map, err_map):
1158 human_ty = struct_name.replace("LDKCResult", "Result")
1160 java_hu_struct += self.hu_struct_file_prefix
1161 java_hu_struct += "public class " + human_ty + " : CommonBase {\n"
1162 java_hu_struct += "\t" + human_ty + "(object _dummy, long ptr) : base(ptr) { }\n"
1163 java_hu_struct += "\t~" + human_ty + "() {\n"
1164 java_hu_struct += "\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n"
1165 java_hu_struct += "\t}\n\n"
1166 java_hu_struct += "\tinternal static " + human_ty + " constr_from_ptr(long ptr) {\n"
1167 java_hu_struct += "\t\tif (bindings." + struct_name.replace("LDK", "") + "_is_ok(ptr)) {\n"
1168 java_hu_struct += "\t\t\treturn new " + human_ty + "_OK(null, ptr);\n"
1169 java_hu_struct += "\t\t} else {\n"
1170 java_hu_struct += "\t\t\treturn new " + human_ty + "_Err(null, ptr);\n"
1171 java_hu_struct += "\t\t}\n"
1172 java_hu_struct += "\t}\n"
1174 java_hu_struct += "\tpublic class " + human_ty + "_OK : " + human_ty + " {\n"
1176 if res_map.java_hu_ty != "void":
1177 java_hu_struct += "\t\tpublic readonly " + res_map.java_hu_ty + " res;\n"
1178 java_hu_struct += "\t\tinternal " + human_ty + "_OK(object _dummy, long ptr) : base(_dummy, ptr) {\n"
1179 if res_map.java_hu_ty == "void":
1181 elif res_map.to_hu_conv is not None:
1182 java_hu_struct += "\t\t\t" + res_map.java_ty + " res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1183 java_hu_struct += "\t\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t\t")
1184 java_hu_struct += "\n\t\t\tthis.res = " + res_map.to_hu_conv_name + ";\n"
1186 java_hu_struct += "\t\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1187 java_hu_struct += "\t\t}\n"
1188 java_hu_struct += "\t}\n\n"
1190 java_hu_struct += "\tpublic class " + human_ty + "_Err : " + human_ty + " {\n"
1191 if err_map.java_hu_ty != "void":
1192 java_hu_struct += "\t\tpublic readonly " + err_map.java_hu_ty + " err;\n"
1193 java_hu_struct += "\t\tinternal " + human_ty + "_Err(object _dummy, long ptr) : base(_dummy, ptr) {\n"
1194 if err_map.java_hu_ty == "void":
1196 elif err_map.to_hu_conv is not None:
1197 java_hu_struct += "\t\t\t" + err_map.java_ty + " err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1198 java_hu_struct += "\t\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t\t")
1199 java_hu_struct += "\n\t\t\tthis.err = " + err_map.to_hu_conv_name + ";\n"
1201 java_hu_struct += "\t\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1202 java_hu_struct += "\t\t}\n"
1204 java_hu_struct += "\t}\n\n"
1205 return java_hu_struct
1207 def map_function(self, argument_types, c_call_string, method_name, meth_n, return_type_info, struct_meth, default_constructor_args, takes_self, takes_self_as_ref, args_known, type_mapping_generator, doc_comment):
1210 out_java_struct = None
1212 out_java += self.native_meth_decl(method_name, return_type_info.java_ty) + "("
1213 out_c += (return_type_info.c_ty)
1214 if return_type_info.ret_conv is not None:
1215 ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1216 have_args = len(argument_types) > 1 or (len(argument_types) > 0 and argument_types[0].c_ty != "void")
1217 out_c += (" " + self.c_fn_name_define_pfx(method_name, have_args))
1219 for idx, arg_conv_info in enumerate(argument_types):
1223 if arg_conv_info.c_ty != "void":
1224 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1225 out_java += (arg_conv_info.java_ty + " _" + arg_conv_info.arg_name) # Add a _ to avoid using reserved words
1227 out_java_struct = ""
1228 extra_java_struct_out = ""
1230 out_java_struct += ("\t// Skipped " + method_name + "\n")
1232 if doc_comment is not None:
1233 out_java_struct += "\t/**\n\t * " + doc_comment.replace("\n", "\n\t * ") + "\n\t */\n"
1234 hu_ret_ty = return_type_info.java_hu_ty
1235 if return_type_info.nullable:
1236 #hu_ret_ty += "?" - apparently mono doesn't support the nullable stuff
1240 out_java_struct += "\tpublic static " + hu_ret_ty + " of("
1241 elif meth_n == "default":
1242 out_java_struct += "\tpublic static " + hu_ret_ty + " with_default("
1244 out_java_struct += "\tpublic static " + hu_ret_ty + " " + meth_n + "("
1245 elif meth_n == "clone_ptr" or (struct_meth.startswith("LDKCResult") and (meth_n == "get_ok" or meth_n == "get_err")):
1246 out_java_struct += "\tinternal " + hu_ret_ty + " " + meth_n + "("
1248 if meth_n == "hash" and return_type_info.java_hu_ty == "long":
1249 extra_java_struct_out = "\tpublic override int GetHashCode() {\n"
1250 extra_java_struct_out += "\t\treturn (int)this.hash();\n"
1251 extra_java_struct_out += "\t}\n"
1252 elif meth_n == "eq" and return_type_info.java_hu_ty == "bool":
1253 extra_java_struct_out = "\tpublic override bool Equals(object o) {\n"
1254 extra_java_struct_out += "\t\tif (!(o is " + struct_meth + ")) return false;\n"
1255 extra_java_struct_out += "\t\treturn this.eq((" + struct_meth + ")o);\n"
1256 extra_java_struct_out += "\t}\n"
1257 if meth_n == "lock":
1258 out_java_struct += "\tpublic " + hu_ret_ty + " do_lock("
1260 out_java_struct += "\tpublic " + hu_ret_ty + " " + meth_n + "("
1261 for idx, arg in enumerate(argument_types):
1263 if not takes_self or idx > 1:
1264 out_java_struct += ", "
1267 if arg.java_ty != "void":
1268 if arg.arg_name in default_constructor_args:
1269 assert not arg.nullable
1270 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1271 if explode_idx != 0:
1272 out_java_struct += (", ")
1273 out_java_struct += (
1274 explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
1276 ty_string = arg.java_hu_ty
1278 #ty_string += "?" - apparently mono doesn't support the nullable stuff
1280 ty_string = self.fully_qualified_hu_ty_path(arg)
1281 out_java_struct += ty_string + " " + arg_name_repl(arg.arg_name, arg.arg_name)
1282 out_java += (");\n")
1284 if out_java_struct is not None:
1285 out_java_struct += (") {\n")
1286 for info in argument_types:
1287 if info.arg_conv is not None:
1288 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1289 if return_type_info.ret_conv is not None:
1290 out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1291 elif return_type_info.c_ty != "void":
1292 out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1295 if c_call_string is None:
1296 out_c += (method_name + "(")
1298 out_c += (c_call_string)
1299 for idx, info in enumerate(argument_types):
1300 if info.arg_conv_name is not None:
1303 elif c_call_string is not None:
1305 out_c += (info.arg_conv_name)
1307 if return_type_info.ret_conv is not None:
1308 out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1311 for info in argument_types:
1312 if info.arg_conv_cleanup is not None:
1313 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1314 if return_type_info.ret_conv is not None:
1315 out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1316 elif return_type_info.c_ty != "void":
1317 out_c += ("\n\treturn ret_val;")
1318 out_c += ("\n}\n\n")
1321 out_java_struct += ("\t\t")
1322 if return_type_info.java_ty != "void":
1323 out_java_struct += (return_type_info.java_ty + " ret = ")
1324 out_java_struct += ("bindings." + method_name + "(")
1325 for idx, info in enumerate(argument_types):
1327 out_java_struct += (", ")
1328 if idx == 0 and takes_self:
1329 out_java_struct += ("this.ptr")
1330 elif info.arg_name in default_constructor_args:
1331 out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1332 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1333 if explode_idx != 0:
1334 out_java_struct += (", ")
1335 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1336 if explode_arg.from_hu_conv is not None:
1337 out_java_struct += (
1338 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1340 out_java_struct += (expl_arg_name)
1341 out_java_struct += (")")
1342 elif info.from_hu_conv is not None:
1343 out_java_struct += arg_name_repl(info.from_hu_conv[0], info.arg_name)
1345 out_java_struct += arg_name_repl(info.arg_name, info.arg_name)
1346 out_java_struct += (");\n")
1348 # Like Java, the C# GC is quite aggressive and can finalize an object while a method
1349 # on it is operating. Unlike Java, this behavior appears to be better documented,
1351 for idx, info in enumerate(argument_types):
1352 if idx == 0 and takes_self:
1353 out_java_struct += ("\t\tGC.KeepAlive(this);\n")
1354 elif info.arg_name in default_constructor_args:
1355 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1356 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1357 out_java_struct += ("\t\tGC.KeepAlive(" + expl_arg_name + ");\n")
1358 elif info.c_ty != "void":
1359 out_java_struct += ("\t\tGC.KeepAlive(" + arg_name_repl(info.arg_name, info.arg_name) + ");\n")
1361 if return_type_info.java_ty == "long" and return_type_info.java_hu_ty != "long":
1362 out_java_struct += "\t\tif (ret >= 0 && ret <= 4096) { return null; }\n"
1364 if return_type_info.to_hu_conv is not None:
1366 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t")
1367 .replace("this", return_type_info.to_hu_conv_name) + "\n")
1369 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1371 for idx, info in enumerate(argument_types):
1372 if idx == 0 and takes_self:
1374 elif info.arg_name in default_constructor_args:
1375 for explode_arg in default_constructor_args[info.arg_name]:
1376 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1377 if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1378 out_java_struct += ("\t\t" +
1379 arg_name_repl(explode_arg.from_hu_conv[1], info.arg_name)
1380 .replace(explode_arg.arg_name, expl_arg_name)
1381 .replace("this", return_type_info.to_hu_conv_name) + ";\n")
1382 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1383 if not takes_self and return_type_info.to_hu_conv_name is not None:
1384 out_java_struct += ("\t\t" + arg_name_repl(info.from_hu_conv[1], info.arg_name)
1385 .replace("this", return_type_info.to_hu_conv_name)
1386 .replace("\n", "\n\t\t") + ";\n")
1388 out_java_struct += ("\t\t" + arg_name_repl(info.from_hu_conv[1], info.arg_name)
1389 .replace("\n", "\n\t\t") + ";\n")
1391 if takes_self and not takes_self_as_ref:
1392 out_java_struct += "\t\t" + argument_types[0].from_hu_conv[1].replace("\n", "\n\t\t").replace("this_arg", "this") + ";\n"
1393 if return_type_info.to_hu_conv_name is not None:
1394 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1395 elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1396 out_java_struct += ("\t\treturn ret;\n")
1397 out_java_struct += ("\t}\n\n")
1399 return (out_java, out_c, out_java_struct + extra_java_struct_out)
1402 with open(self.outdir + "src/org/ldk/impl/bindings.cs", "a") as bindings:
1403 for fn_suffix in self.function_ptrs:
1404 jret = self.function_ptrs[fn_suffix]["ret"][0]
1405 jargs = self.function_ptrs[fn_suffix]["args"][0]
1408 static {jret} c_callback_{fn_suffix}(int obj_ptr, int fn_id{jargs}) {{
1409 if (obj_ptr >= js_objs.Count) {{
1410 Console.Error.WriteLine("Got function call on unknown/free'd JS object in {fn_suffix}");
1411 Console.Error.Flush();
1412 Environment.Exit(42);
1414 object obj = js_objs[obj_ptr].Target;
1416 Console.Error.WriteLine("Got function call on GC'd JS object in {fn_suffix}");
1417 Console.Error.Flush();
1418 Environment.Exit(43);
1421 bindings.write("\t\tswitch (fn_id) {\n")
1422 for f in self.function_ptrs[fn_suffix]:
1423 if f != "ret" and f != "args" and f != "call":
1424 bindings.write(f"""\t\t\tcase {str(f)}:
1425 if (!(obj is {self.function_ptrs[fn_suffix][f][0]})) {{
1426 Console.Error.WriteLine("Got function call to object that wasn't a {self.function_ptrs[fn_suffix][f][0]} in {fn_suffix}");
1427 Console.Error.Flush();
1428 Environment.Exit(44);
1430 call = f"(({self.function_ptrs[fn_suffix][f][0]})obj).{self.function_ptrs[fn_suffix][f][1]}({self.function_ptrs[fn_suffix][f][2]});"
1432 bindings.write("\t\t\t\treturn " + call)
1434 bindings.write("\t\t\t\t" + call + "\n\t\t\t\treturn;")
1435 bindings.write("\n")
1437 bindings.write(f"""\t\t\tdefault:
1438 Console.Error.WriteLine("Got unknown function call with id " + fn_id + " from C in {fn_suffix}");
1439 Console.Error.Flush();
1440 Environment.Exit(45);
1441 return{" false" if jret == "bool" else " 0" if jret != "void" else ""};
1444 public delegate {jret} {fn_suffix}_callback(int obj_ptr, int fn_id{jargs});
1446 bindings.write(self.native_meth_decl(f"register_{fn_suffix}_invoker", "int") + f"({fn_suffix}_callback callee);\n")
1447 # Easiest way to get a static run is just define a variable, even if we dont care
1448 bindings.write(f"\tstatic int _run_{fn_suffix}_registration = register_{fn_suffix}_invoker(c_callback_{fn_suffix});")