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); }
153 self.witness_program_defn = """public class WitnessProgram : CommonBase {
154 /** The witness program bytes themselves */
155 public readonly byte[] program;
156 /** The witness version */
157 public readonly WitnessVersion version;
159 internal WitnessProgram(object _dummy, long ptr) : base(ptr) {
160 this.program = InternalUtils.decodeUint8Array(bindings.WitnessProgram_get_program(ptr));
161 this.version = new WitnessVersion(bindings.WitnessProgram_get_version(ptr));
163 static private long check_args(byte[] program, WitnessVersion version) {
164 if (program.Length < 2 || program.Length > 40) throw new ArgumentException();
165 if (version.getVal() == 0 && program.Length != 20 && program.Length != 32) throw new ArgumentException();
166 return InternalUtils.encodeUint8Array(program);
168 public WitnessProgram(byte[] program, WitnessVersion version) :
169 this(null, bindings.WitnessProgram_new(version.getVal(), check_args(program, version))) {}
172 if (ptr != 0) { bindings.WitnessProgram_free(ptr); }
176 self.c_file_pfx = """
177 // On OSX jlong (ie long long) is not equivalent to int64_t, so we override here
178 #define int64_t jlong
179 #include <lightning.h>
181 #include <stdatomic.h>
184 #define LIKELY(v) __builtin_expect(!!(v), 1)
185 #define UNLIKELY(v) __builtin_expect(!!(v), 0)
189 self.c_file_pfx = self.c_file_pfx + "#include <stdio.h>\n#define DEBUG_PRINT(...) fprintf(stderr, __VA_ARGS__)\n"
191 if not DEBUG or sys.platform == "darwin":
192 self.c_file_pfx = self.c_file_pfx + """#define do_MALLOC(a, _b, _c) malloc(a)
193 #define MALLOC(a, _) malloc(a)
194 #define FREE(p) if ((uint64_t)(p) > 4096) { free(p); }
195 #define CHECK_ACCESS(p)
196 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
199 self.c_file_pfx += """#define DO_ASSERT(a) (void)(a)
203 self.c_file_pfx = self.c_file_pfx + """#include <assert.h>
204 // Always run a, then assert it is true:
205 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
206 // Assert a is true or do nothing
207 #define CHECK(a) DO_ASSERT(a)
209 void __attribute__((constructor)) debug_log_version() {
210 if (check_get_ldk_version() == NULL)
211 DEBUG_PRINT("LDK version did not match the header we built against\\n");
212 if (check_get_ldk_bindings_version() == NULL)
213 DEBUG_PRINT("LDK C Bindings version did not match the header we built against\\n");
217 if sys.platform != "darwin":
218 self.c_file_pfx += """
219 // Running a leak check across all the allocations and frees of the JDK is a mess,
220 // so instead we implement our own naive leak checker here, relying on the -wrap
221 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
222 // and free'd in Rust or C across the generated bindings shared library.
226 self.c_file_pfx = self.c_file_pfx + "#include <execinfo.h>\n"
227 self.c_file_pfx = self.c_file_pfx + """
230 static pthread_mutex_t allocation_mtx;
232 void __attribute__((constructor)) init_mtx() {
233 DO_ASSERT(!pthread_mutex_init(&allocation_mtx, NULL));
237 typedef struct allocation {
238 struct allocation* next;
240 const char* struct_name;
243 unsigned long alloc_len;
245 static allocation* allocation_ll = NULL;
247 void* __real_malloc(size_t len);
248 void* __real_calloc(size_t nmemb, size_t len);
249 static void new_allocation(void* res, const char* struct_name, size_t len) {
250 allocation* new_alloc = __real_malloc(sizeof(allocation));
251 new_alloc->ptr = res;
252 new_alloc->struct_name = struct_name;
253 new_alloc->bt_len = backtrace(new_alloc->bt, BT_MAX);
254 new_alloc->alloc_len = len;
255 DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
256 new_alloc->next = allocation_ll;
257 allocation_ll = new_alloc;
258 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
260 static void* do_MALLOC(size_t len, const char* struct_name, int lineno) {
261 void* res = __real_malloc(len);
262 new_allocation(res, struct_name, lineno);
265 #define MALLOC(len, struct_name) do_MALLOC(len, struct_name, __LINE__)
267 void __real_free(void* ptr);
268 static void alloc_freed(void* ptr) {
269 allocation* p = NULL;
270 DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
271 allocation* it = allocation_ll;
272 while (it->ptr != ptr) {
273 p = it; it = it->next;
275 DEBUG_PRINT("ERROR: Tried to free unknown pointer %p at:\\n", ptr);
277 int bt_len = backtrace(bt, BT_MAX);
278 backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
279 DEBUG_PRINT("\\n\\n");
280 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
281 return; // addrsan should catch malloc-unknown and print more info than we have
284 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
285 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
286 DO_ASSERT(it->ptr == ptr);
289 static void FREE(void* ptr) {
290 if ((uint64_t)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
295 void* __wrap_malloc(size_t len) {
296 void* res = __real_malloc(len);
297 new_allocation(res, "malloc call", len);
300 void* __wrap_calloc(size_t nmemb, size_t len) {
301 void* res = __real_calloc(nmemb, len);
302 new_allocation(res, "calloc call", len);
305 void __wrap_free(void* ptr) {
306 if (ptr == NULL) return;
311 static void CHECK_ACCESS(const void* ptr) {
312 DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
313 allocation* it = allocation_ll;
314 while (it->ptr != ptr) {
317 DEBUG_PRINT("ERROR: Tried to access unknown pointer %p at:\\n", ptr);
319 int bt_len = backtrace(bt, BT_MAX);
320 backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
321 DEBUG_PRINT("\\n\\n");
322 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
323 return; // addrsan should catch and print more info than we have
326 DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
328 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
329 if (v.is_owned && v.inner != NULL) { \\
330 const void *p = __unmangle_inner_ptr(v.inner); \\
336 void* __real_realloc(void* ptr, size_t newlen);
337 void* __wrap_realloc(void* ptr, size_t len) {
338 if (ptr != NULL) alloc_freed(ptr);
339 void* res = __real_realloc(ptr, len);
340 new_allocation(res, "realloc call", len);
343 void __wrap_reallocarray(void* ptr, size_t new_sz) {
344 // Rust doesn't seem to use reallocarray currently
348 void __attribute__((destructor)) check_leaks() {
349 unsigned long alloc_count = 0;
350 unsigned long alloc_size = 0;
351 DEBUG_PRINT("The following LDK-allocated blocks still remain.\\n");
352 DEBUG_PRINT("Note that this is only accurate if System.GC.Collect(); GC.WaitForPendingFinalizers();\\n");
353 DEBUG_PRINT("was called prior to exit after all LDK objects were out of scope.\\n");
354 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
355 DEBUG_PRINT("%s %p (%lu bytes) remains:\\n", a->struct_name, a->ptr, a->alloc_len);
356 backtrace_symbols_fd(a->bt, a->bt_len, STDERR_FILENO);
357 DEBUG_PRINT("\\n\\n");
359 alloc_size += a->alloc_len;
361 DEBUG_PRINT("%lu allocations remained for %lu bytes.\\n", alloc_count, alloc_size);
362 DEBUG_PRINT("Note that this is only accurate if System.GC.Collect(); GC.WaitForPendingFinalizers()\\n");
363 DEBUG_PRINT("was called prior to exit after all LDK objects were out of scope.\\n");
366 self.c_file_pfx = self.c_file_pfx + """
368 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
369 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
370 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
371 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
373 _Static_assert(sizeof(void*) <= 8, "Pointers must fit into 64 bits");
375 // Int types across Windows/Linux are different, so make sure we're using the right headers.
376 _Static_assert(sizeof(void*) == sizeof(uintptr_t), "stdints must be correct");
377 _Static_assert(sizeof(void*) == sizeof(intptr_t), "stdints must be correct");
378 _Static_assert(sizeof(uint64_t) == 8, "stdints must be correct");
379 _Static_assert(sizeof(int64_t) == 8, "stdints must be correct");
380 _Static_assert(sizeof(uint32_t) == 4, "stdints must be correct");
381 _Static_assert(sizeof(int32_t) == 4, "stdints must be correct");
382 _Static_assert(sizeof(uint16_t) == 2, "stdints must be correct");
383 _Static_assert(sizeof(int16_t) == 2, "stdints must be correct");
384 _Static_assert(sizeof(uint8_t) == 1, "stdints must be correct");
385 _Static_assert(sizeof(int8_t) == 1, "stdints must be correct");
387 #define DECL_ARR_TYPE(ty, name) \\
388 struct name##array { \\
389 uint64_t arr_len; /* uint32_t would suffice but we want to align uint64_ts as well */ \\
392 typedef struct name##array * name##Array; \\
393 static inline name##Array init_##name##Array(size_t arr_len, int lineno) { \\
394 name##Array arr = (name##Array)do_MALLOC(arr_len * sizeof(ty) + sizeof(uint64_t), #name" array init", lineno); \\
395 arr->arr_len = arr_len; \\
399 DECL_ARR_TYPE(int64_t, int64_t);
400 DECL_ARR_TYPE(uint64_t, uint64_t);
401 DECL_ARR_TYPE(int8_t, int8_t);
402 DECL_ARR_TYPE(int16_t, int16_t);
403 DECL_ARR_TYPE(uint32_t, uint32_t);
404 DECL_ARR_TYPE(void*, ptr);
405 DECL_ARR_TYPE(char, char);
406 typedef charArray jstring;
408 static inline jstring str_ref_to_cs(const char* chars, size_t len) {
409 charArray arr = init_charArray(len, __LINE__);
410 memcpy(arr->elems, chars, len);
413 static inline LDKStr str_ref_to_owned_c(const jstring str) {
414 char* newchars = MALLOC(str->arr_len + 1, "String chars");
415 memcpy(newchars, str->elems, str->arr_len);
416 newchars[str->arr_len] = 0;
420 .chars_is_owned = true
425 typedef bool jboolean;
427 int64_t CS_LDK_allocate_buffer(int64_t len) {
428 return (int64_t)MALLOC(len, "C#-requested buffer");
431 void CS_LDK_free_buffer(int64_t buf) {
435 jstring CS_LDK_get_ldk_c_bindings_version() {
436 return str_ref_to_cs(check_get_ldk_bindings_version(), strlen(check_get_ldk_bindings_version()));
438 jstring CS_LDK_get_ldk_version() {
439 return str_ref_to_cs(check_get_ldk_version(), strlen(check_get_ldk_version()));
443 self.c_version_file = """const char* CS_LDK_get_lib_version_string() {
444 return "<git_version_ldk_garbagecollected>";
447 self.hu_struct_file_prefix = """using org.ldk.impl;
452 namespace org { namespace ldk { namespace structs {
455 self.hu_struct_file_suffix = "} } }\n"
456 self.c_fn_args_pfx = ""
457 self.c_fn_ty_pfx = ""
458 self.file_ext = ".cs"
459 self.ptr_c_ty = "int64_t"
460 self.ptr_native_ty = "long"
461 self.u128_native_ty = "UInt128"
462 self.usize_c_ty = "int64_t"
463 self.usize_native_ty = "long"
464 self.native_zero_ptr = "0"
465 self.unitary_enum_c_ty = "int32_t"
466 self.ptr_arr = "ptrArray"
467 self.is_arr_some_check = ("", " != NULL")
468 self.get_native_arr_len_call = ("", "->arr_len")
470 self.bindings_footer_wip = "\tstatic bindings() {\n"
471 def bindings_footer(self):
474 def native_meth_decl(self, meth_name, ret_ty_str):
475 return "\t[DllImport (\"ldkcsharp\", EntryPoint=\"CS_LDK_" + meth_name + "\")] public static extern " + ret_ty_str + " " + meth_name
477 def c_fn_name_define_pfx(self, fn_name, have_args):
478 return " CS_LDK_" + fn_name + "("
480 def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
482 def create_native_arr_call(self, arr_len, ty_info):
483 if ty_info.c_ty == "ptrArray":
484 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"))
485 return "init_" + ty_info.c_ty + "(" + arr_len + ", __LINE__)"
486 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
487 if ty_info.c_ty == "int8_tArray":
488 return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
489 elif ty_info.c_ty == "int16_tArray":
490 return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + " * 2)")
493 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
494 if ty_info.c_ty == "int8_tArray" or ty_info.c_ty == "int16_tArray":
497 if ty_info.c_ty == "int16_tArray":
498 byte_len = arr_len + " * 2"
499 return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + byte_len + "); FREE(" + arr_name + ")"
501 if ty_info.c_ty == "ptrArray":
502 return "(void*) " + arr_name + "->elems"
504 return arr_name + "->elems"
505 def get_native_arr_elem(self, arr_name, idxc, ty_info):
506 assert False # Only called if above is None
507 def get_native_arr_ptr_call(self, ty_info):
508 if ty_info.subty is not None:
509 return "(" + ty_info.subty.c_ty + "*)(((uint8_t*)", ") + 8)"
510 return "(" + ty_info.c_ty + "*)(((uint8_t*)", ") + 8)"
511 def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
513 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
514 if ty_info.c_ty == "int8_tArray":
515 return "FREE(" + arr_name + ");"
517 return "FREE(" + arr_name + ")"
519 def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty, is_nullable):
520 if elem_ty.java_hu_ty == "UInt5":
521 return "InternalUtils.convUInt5Array(" + arr_name + ")"
522 elif elem_ty.java_hu_ty == "WitnessVersion":
523 return "InternalUtils.convWitnessVersionArray(" + arr_name + ")"
525 return "InternalUtils.mapArray(" + arr_name + ", " + conv_name + " => " + elem_ty.from_hu_conv[0] + ")"
527 def str_ref_to_native_call(self, var_name, str_len):
528 return "str_ref_to_cs(" + var_name + ", " + str_len + ")"
529 def str_ref_to_c_call(self, var_name):
530 return "str_ref_to_owned_c(" + var_name + ")"
531 def str_to_hu_conv(self, var_name):
532 return "string " + var_name + "_conv = InternalUtils.decodeString(" + var_name + ");"
533 def str_from_hu_conv(self, var_name):
534 return ("InternalUtils.encodeString(" + var_name + ")", "")
538 for fn_suffix in self.function_ptrs:
539 cret = self.function_ptrs[fn_suffix]["ret"][1]
540 cargs = self.function_ptrs[fn_suffix]["args"][1]
542 typedef {cret} (*invoker_{fn_suffix})(int obj_ptr, int fn_id{cargs});
543 static invoker_{fn_suffix} js_invoke_function_{fn_suffix};
544 int CS_LDK_register_{fn_suffix}_invoker(invoker_{fn_suffix} invoker) {{
545 js_invoke_function_{fn_suffix} = invoker;
552 def var_decl_statement(self, ty_string, var_name, statement):
553 return ty_string + " " + var_name + " = " + statement
555 def get_java_arr_len(self, arr_name):
556 return "InternalUtils.getArrayLength(" + arr_name + ")"
558 def get_java_arr_elem(self, elem_ty, arr_name, idx):
559 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":
560 return "InternalUtils.getU64ArrayElem(" + arr_name + ", " + idx + ")"
561 elif elem_ty.rust_obj == "LDKU5":
562 return "InternalUtils.getU8ArrayElem(" + arr_name + ", " + idx + ")"
563 elif elem_ty.rust_obj == "LDKStr":
564 return "InternalUtils.getU32ArrayElem(" + arr_name + ", " + idx + ")"
568 def constr_hu_array(self, ty_info, arr_len):
569 base_ty = ty_info.subty.java_hu_ty.split("[")[0].split("<")[0]
570 conv = "new " + base_ty + "[" + arr_len + "]"
571 if "[" in ty_info.subty.java_hu_ty.split("<")[0]:
572 # Do a bit of a dance to move any excess [] to the end
573 conv += "[" + ty_info.subty.java_hu_ty.split("<")[0].split("[")[1]
575 def cleanup_converted_native_array(self, ty_info, arr_name):
576 return "bindings.free_buffer(" + arr_name + ");"
578 def primitive_arr_from_hu(self, arr_ty, fixed_len, arr_name):
579 mapped_ty = arr_ty.subty
581 if arr_ty.rust_obj == "LDKU128":
582 return ("InternalUtils.encodeUint8Array(" + arr_name + ".getLEBytes())", "")
583 if fixed_len is not None:
584 inner = "InternalUtils.check_arr_len(" + arr_name + ", " + fixed_len + ")"
585 if mapped_ty.c_ty.endswith("Array"):
586 return ("InternalUtils.encodeUint64Array(" + inner + ")", "")
587 elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
588 return ("InternalUtils.encodeUint8Array(" + inner + ")", "")
589 elif mapped_ty.c_ty == "uint16_t" or mapped_ty.c_ty == "int16_t":
590 return ("InternalUtils.encodeUint16Array(" + inner + ")", "")
591 elif mapped_ty.c_ty == "uint32_t":
592 return ("InternalUtils.encodeUint32Array(" + inner + ")", "")
593 elif mapped_ty.c_ty == "int64_t" or mapped_ty.c_ty == "uint64_t" or mapped_ty.rust_obj == "LDKStr":
594 return ("InternalUtils.encodeUint64Array(" + inner + ")", "")
596 print(mapped_ty.c_ty)
599 def primitive_arr_to_hu(self, arr_ty, fixed_len, arr_name, conv_name):
600 mapped_ty = arr_ty.subty
601 if arr_ty.rust_obj == "LDKU128":
602 return "org.ldk.util.UInt128 " + conv_name + " = new org.ldk.util.UInt128(" + arr_name + ");"
603 elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
604 return "byte[] " + conv_name + " = InternalUtils.decodeUint8Array(" + arr_name + ");"
605 elif mapped_ty.c_ty == "uint16_t" or mapped_ty.c_ty == "int16_t":
606 return "short[] " + conv_name + " = InternalUtils.decodeUint16Array(" + arr_name + ");"
607 elif mapped_ty.c_ty == "uint64_t" or mapped_ty.c_ty == "int64_t":
608 return "long[] " + conv_name + " = InternalUtils.decodeUint64Array(" + arr_name + ");"
612 def java_arr_ty_str(self, elem_ty_str):
615 def for_n_in_range(self, n, minimum, maximum):
616 return "for (int " + n + " = " + minimum + "; " + n + " < " + maximum + "; " + n + "++) {"
617 def for_n_in_arr(self, n, arr_name, arr_elem_ty):
618 return ("foreach (" + arr_elem_ty.java_hu_ty + " " + n + " in " + arr_name + ") { ", " }")
620 def get_ptr(self, var):
622 def set_null_skip_free(self, var):
623 return var + ".ptr" + " = 0;"
625 def add_ref(self, holder, referent):
626 return "if (" + holder + " != null) { " + holder + ".ptrs_to.AddLast(" + referent + "); }"
628 def fully_qualified_hu_ty_path(self, ty):
629 if ty.java_fn_ty_arg.startswith("L") and ty.java_fn_ty_arg.endswith(";"):
631 if ty.java_hu_ty == "UnqualifiedError" or ty.java_hu_ty == "UInt128" or ty.java_hu_ty == "UInt5" or ty.java_hu_ty == "WitnessVersion":
632 return "org.ldk.util." + ty.java_hu_ty
633 if not ty.is_native_primitive and ty.rust_obj is not None and not "[]" in ty.java_hu_ty:
634 return "org.ldk.structs." + ty.java_hu_ty
637 def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
638 out_java_enum = "namespace org { namespace ldk { namespace enums {"
642 out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_cs(int32_t ord) {\n"
643 out_c += "\tswitch (ord) {\n"
645 if enum_doc_comment is not None:
646 out_java_enum += "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
647 out_java_enum += "public enum " + struct_name + " {\n"
649 for var, var_docs in variants:
650 if var_docs is not None:
651 out_java_enum += "\t/**\n\t * " + var_docs.replace("\n", "\n\t * ") + "\n\t */\n"
652 out_java_enum += "\t" + var + ",\n"
653 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
656 out_c += "\t\tdefault: abort();\n"
660 out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_cs(LDK" + struct_name + " val) {\n"
661 out_c = out_c + "\tswitch (val) {\n"
663 for var, _ in variants:
664 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
666 out_c = out_c + "\t\tdefault: abort();\n"
667 out_c = out_c + "\t}\n"
668 out_c = out_c + "}\n"
670 return (out_c, out_java_enum + "} } }\n", out_java)
672 def c_unitary_enum_to_native_call(self, ty_info):
673 return (ty_info.rust_obj + "_to_cs(", ")")
674 def native_unitary_enum_to_c_call(self, ty_info):
675 return (ty_info.rust_obj + "_from_cs(", ")")
677 def c_complex_enum_pfx(self, struct_name, variants, init_meth_jty_strs):
680 out_c = out_c + "static jclass " + struct_name + "_" + var + "_class = NULL;\n"
681 out_c = out_c + "static jmethodID " + struct_name + "_" + var + "_meth = NULL;\n"
682 out_c += "void" + self.c_fn_name_define_pfx(struct_name.replace("_", "_1") + "_init", True) + self.c_fn_args_pfx + ") {\n"
683 for var_name in variants:
684 out_c += "\t" + struct_name + "_" + var_name + "_class =\n"
685 out_c += "\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"org/ldk/impl/bindings$" + struct_name + "$" + var_name + "\"));\n"
686 out_c += "\tCHECK(" + struct_name + "_" + var_name + "_class != NULL);\n"
687 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"
688 out_c += "\tCHECK(" + struct_name + "_" + var_name + "_meth != NULL);\n"
689 out_c = out_c + "}\n"
692 def c_complex_enum_pass_ty(self, struct_name):
695 def c_constr_native_complex_enum(self, struct_name, variant, c_params):
696 ret = "(*env)->NewObject(env, " + struct_name + "_" + variant + "_class, " + struct_name + "_" + variant + "_meth"
697 for param in c_params:
698 ret = ret + ", " + param
701 def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
702 out_typescript_bindings = ""
703 super_instantiator = ""
704 bindings_instantiator = ""
705 pointer_to_adder = ""
706 impl_constructor_arguments = ""
707 for var in flattened_field_var_conversions:
708 if isinstance(var, ConvInfo):
709 impl_constructor_arguments += f", {var.java_hu_ty} {var.arg_name}"
710 if var.from_hu_conv is not None:
711 bindings_instantiator += ", " + var.from_hu_conv[0]
712 if var.from_hu_conv[1] != "":
713 pointer_to_adder += "\t\t\t" + var.from_hu_conv[1] + ";\n"
715 bindings_instantiator += ", " + first_to_lower(var.arg_name)
717 bindings_instantiator += ", " + first_to_lower(var[1]) + ".instance_idx"
718 pointer_to_adder += "\t\timpl_holder.held.ptrs_to.AddLast(" + first_to_lower(var[1]) + ");\n"
719 impl_constructor_arguments += f", {var[0].replace('LDK', '')}Interface {first_to_lower(var[1])}_impl"
721 super_constructor_statements = ""
722 trait_constructor_arguments = ""
723 for var in field_var_conversions:
724 if isinstance(var, ConvInfo):
725 trait_constructor_arguments += ", " + var.arg_name
727 super_constructor_statements += "\t\t" + var[1] + " " + first_to_lower(var[1]) + " = " + var[1] + ".new_impl(" + first_to_lower(var[1]) + "_impl"
728 super_instantiator = ""
729 for suparg in var[2]:
730 if isinstance(suparg, ConvInfo):
731 super_instantiator += ", " + suparg.arg_name
733 super_instantiator += ", " + first_to_lower(suparg[1]) + "_impl"
734 super_constructor_statements += super_instantiator + ");\n"
735 trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".instance_idx"
736 for suparg in var[2]:
737 if isinstance(suparg, ConvInfo):
738 trait_constructor_arguments += ", " + suparg.arg_name
740 # Blindly assume that we can just strip the first arg to build the args for the supertrait
741 super_constructor_statements += "\t\t" + suparg[1] + " " + first_to_lower(suparg[1]) + " = " + suparg[1] + ".new_impl(" + super_instantiator.split(", ", 1)[1] + ");\n"
742 trait_constructor_arguments += ", " + suparg[1]
744 # BUILD INTERFACE METHODS
746 java_trait_wrapper = "\tprivate class " + struct_name + "Holder { internal " + struct_name.replace("LDK", "") + " held; }\n"
747 java_trait_wrapper += "\tprivate class " + struct_name + "Impl : bindings." + struct_name + " {\n"
748 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"
749 java_trait_wrapper += "\t\tprivate " + struct_name.replace("LDK", "") + "Interface arg;\n"
750 java_trait_wrapper += "\t\tprivate " + struct_name + "Holder impl_holder;\n"
752 for fn_line in field_function_lines:
753 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
754 fn_name = fn_line.fn_name
755 if fn_name == "lock": # reserved symbol
757 java_trait_wrapper += "\t\tpublic " + fn_line.ret_ty_info.java_ty + " " + fn_name + "("
759 for idx, arg_conv_info in enumerate(fn_line.args_ty):
761 java_trait_wrapper += ", "
762 java_trait_wrapper += arg_conv_info.java_ty + " _" + arg_conv_info.arg_name
764 java_trait_wrapper += ") {\n"
766 for arg_info in fn_line.args_ty:
767 if arg_info.to_hu_conv is not None:
768 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"
770 if fn_line.ret_ty_info.java_ty != "void":
771 java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_name + "("
773 java_trait_wrapper += "\t\t\targ." + fn_name + "("
775 for idx, arg_info in enumerate(fn_line.args_ty):
777 java_trait_wrapper += ", "
778 if arg_info.to_hu_conv_name is not None:
779 java_trait_wrapper += arg_info.to_hu_conv_name.replace(arg_info.arg_name, "_" + arg_info.arg_name)
781 java_trait_wrapper += "_" + arg_info.arg_name
783 java_trait_wrapper += ");\n"
784 java_trait_wrapper += "\t\t\t\tGC.KeepAlive(arg);\n"
785 if fn_line.ret_ty_info.java_ty != "void":
786 if fn_line.ret_ty_info.from_hu_conv is not None:
787 java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.java_ty + " result = " + fn_line.ret_ty_info.from_hu_conv[0] + ";\n"
788 if fn_line.ret_ty_info.from_hu_conv[1] != "":
789 java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held") + ";\n"
790 java_trait_wrapper += "\t\t\treturn result;\n"
792 java_trait_wrapper += "\t\t\treturn ret;\n"
793 java_trait_wrapper += "\t\t}\n"
794 java_trait_wrapper += "\t}"
796 out_java_interface = ""
798 for fn_line in field_function_lines:
799 java_method_descriptor = ""
800 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
801 out_java_interface += "\t/**" + fn_line.docs.replace("\n", "\n\t * ") + "\n\t */\n"
802 out_java_interface += "\t" + fn_line.ret_ty_info.java_hu_ty + " " + fn_line.fn_name + "("
804 for idx, arg_conv_info in enumerate(fn_line.args_ty):
806 out_java_interface += ", "
807 out_java_interface += f"{arg_conv_info.java_hu_ty} {safe_arg_name(arg_conv_info.arg_name)}"
808 java_method_descriptor += arg_conv_info.java_fn_ty_arg
809 out_java_interface += f");\n"
810 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
811 java_methods.append((fn_line.fn_name, java_method_descriptor))
813 formatted_trait_docs = trait_doc_comment.replace("\n", "\n * ")
814 out_typescript_human = f"""
815 {self.hu_struct_file_prefix}
817 /** An implementation of {struct_name.replace("LDK","")} */
818 public interface {struct_name.replace("LDK", "")}Interface {{
819 {out_java_interface}}}
822 * {formatted_trait_docs}
824 public class {struct_name.replace("LDK","")} : CommonBase {{
825 internal bindings.{struct_name} bindings_instance;
826 internal long instance_idx;
828 internal {struct_name.replace("LDK","")}(object _dummy, long ptr) : base(ptr) {{ bindings_instance = null; }}
829 ~{struct_name.replace("LDK","")}() {{
830 if (ptr != 0) {{ bindings.{struct_name.replace("LDK","")}_free(ptr); }}
835 /** Creates a new instance of {struct_name.replace("LDK","")} from a given implementation */
836 public static {struct_name.replace("LDK", "")} new_impl({struct_name.replace("LDK", "")}Interface arg{impl_constructor_arguments}) {{
837 {struct_name}Holder impl_holder = new {struct_name}Holder();
838 {struct_name}Impl impl = new {struct_name}Impl(arg, impl_holder);
839 {super_constructor_statements} long[] ptr_idx = bindings.{struct_name}_new(impl{bindings_instantiator});
841 impl_holder.held = new {struct_name.replace("LDK", "")}(null, ptr_idx[0]);
842 impl_holder.held.instance_idx = ptr_idx[1];
843 impl_holder.held.bindings_instance = impl;
844 {pointer_to_adder} return impl_holder.held;
849 out_typescript_bindings += "\tpublic interface " + struct_name + " {\n"
851 for fn_line in field_function_lines:
852 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
853 out_typescript_bindings += f"\t\t{fn_line.ret_ty_info.java_ty} {fn_line.fn_name}("
855 for idx, arg_conv_info in enumerate(fn_line.args_ty):
857 out_typescript_bindings = out_typescript_bindings + ", "
858 out_typescript_bindings += f"{arg_conv_info.java_ty} {safe_arg_name(arg_conv_info.arg_name)}"
860 out_typescript_bindings += f");\n"
862 out_typescript_bindings += "\t}\n"
864 c_call_extra_args = ""
865 native_fn_args = "long impl_idx"
866 for var in flattened_field_var_conversions:
867 if isinstance(var, ConvInfo):
868 native_fn_args += ", " + var.java_ty + " " + var.arg_name
870 native_fn_args += ", long " + var[1]
871 out_typescript_bindings += self.native_meth_decl(struct_name + "_new", "long") + "_native(" + native_fn_args + ");\n"
872 out_typescript_bindings += f"\tpublic static long[] {struct_name}_new({struct_name} impl"
873 for var in flattened_field_var_conversions:
874 if isinstance(var, ConvInfo):
875 out_typescript_bindings += f", {var.java_ty} {var.arg_name}"
876 c_call_extra_args += f", {var.arg_name}"
878 out_typescript_bindings += f", long {var[1]}"
879 c_call_extra_args += f", {var[1]}"
882 out_typescript_bindings += f""") {{
883 long new_obj_idx = js_objs.Count;
885 for (; i < js_objs.Count; i++) {{
886 if (js_objs[i] == null || !js_objs[i].IsAlive) {{ new_obj_idx = i; break; }}
888 if (i == js_objs.Count) {{
889 js_objs.Add(new WeakReference(impl));
891 js_objs[i] = new WeakReference(impl);
893 long[] ret = new long[2];
894 ret[0] = {struct_name}_new_native(i{c_call_extra_args});
900 # Now that we've written out our java code (and created java_meths), generate C
901 out_c = "typedef struct " + struct_name + "_JCalls {\n"
902 out_c += "\tatomic_size_t refcnt;\n"
903 out_c += "\tuint32_t instance_ptr;\n"
904 for var in flattened_field_var_conversions:
905 if isinstance(var, ConvInfo):
906 # We're a regular ol' field
910 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
911 out_c = out_c + "} " + struct_name + "_JCalls;\n"
913 for fn_line in field_function_lines:
914 if fn_line.fn_name == "free":
915 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
916 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
917 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
918 out_c = out_c + "\t\tFREE(j_calls);\n"
919 out_c = out_c + "\t}\n}\n"
921 for idx, fn_line in enumerate(field_function_lines):
922 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
923 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
924 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
925 if fn_line.self_is_const:
926 out_c = out_c + "const void* this_arg"
928 out_c = out_c + "void* this_arg"
930 for idx, arg in enumerate(fn_line.args_ty):
931 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
933 out_c = out_c + ") {\n"
934 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
936 for arg_info in fn_line.args_ty:
937 if arg_info.ret_conv is not None:
938 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
939 out_c = out_c + arg_info.arg_name
940 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
942 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
944 fn_java_callback_args = ""
945 fn_c_callback_args = ""
946 fn_callback_call_args = ""
947 fn_suffix = ty_to_c(fn_line.ret_ty_info.java_ty, fn_line.ret_ty_info) + "_"
949 for arg_info in fn_line.args_ty:
950 fn_suffix += ty_to_c(arg_info.java_ty, arg_info)
951 fn_java_callback_args += ", " + arg_info.java_ty + " " + chr(ord("a") + idx)
952 if arg_info.c_ty.endswith("Array") or arg_info.c_ty == "jstring":
953 fn_c_callback_args += ", int64_t " + chr(ord("a") + idx)
955 fn_c_callback_args += ", " + arg_info.c_ty + " " + chr(ord("a") + idx)
957 fn_callback_call_args += ", "
958 fn_callback_call_args += chr(ord("a") + idx)
960 if fn_line.ret_ty_info.c_ty.endswith("Array"):
961 out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (" + fn_line.ret_ty_info.c_ty + ")"
962 out_c += "js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
963 elif fn_line.ret_ty_info.java_ty == "void":
964 out_c = out_c + "\tjs_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
965 elif fn_line.ret_ty_info.java_hu_ty == "string":
966 out_c += "\tjstring ret = (jstring)js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
967 elif fn_line.ret_ty_info.arg_conv is None:
968 out_c += "\treturn js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
970 out_c += "\tuint64_t ret = js_invoke_function_" + fn_suffix + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
972 if fn_suffix not in self.function_ptrs:
973 caller_ret_c_ty = fn_line.ret_ty_info.c_ty
974 if fn_line.ret_ty_info.c_ty.endswith("Array") or fn_line.ret_ty_info.c_ty == "jstring":
975 caller_ret_c_ty = "int64_t"
976 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]}
977 self.function_ptrs[fn_suffix][self.function_ptr_counter] = (struct_name, fn_line.fn_name, fn_callback_call_args)
978 self.function_ptr_counter += 1
980 for idx, arg_info in enumerate(fn_line.args_ty):
981 if arg_info.ret_conv is not None:
982 if arg_info.c_ty.endswith("Array") or arg_info.c_ty == "jstring":
983 out_c += ", (int64_t)" + arg_info.ret_conv_name
985 out_c += ", " + arg_info.ret_conv_name
987 assert False # TODO: Would we need some conversion here?
988 out_c += ", (int64_t)" + arg_info.arg_name
989 out_c = out_c + ");\n"
990 if fn_line.ret_ty_info.arg_conv is not None:
991 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"
993 out_c = out_c + "}\n"
995 # Write out a clone function whether we need one or not, as we use them in moving to rust
996 out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
997 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
998 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
999 for var in flattened_field_var_conversions:
1000 if not isinstance(var, ConvInfo):
1001 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[2].replace(".", "->") + "->refcnt, 1, memory_order_release);\n"
1002 out_c = out_c + "}\n"
1004 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (int64_t o"
1005 for var in flattened_field_var_conversions:
1006 if isinstance(var, ConvInfo):
1007 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1009 out_c = out_c + ", int64_t " + var[1]
1010 out_c = out_c + ") {\n"
1012 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
1013 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
1014 out_c = out_c + "\tcalls->instance_ptr = o;\n"
1016 for (fn_name, java_meth_descr) in java_meths:
1017 if fn_name != "free" and fn_name != "cloned":
1018 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
1019 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
1021 for var in flattened_field_var_conversions:
1022 if isinstance(var, ConvInfo) and var.arg_conv is not None:
1023 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
1024 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
1025 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
1026 for fn_line in field_function_lines:
1027 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1028 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
1029 elif fn_line.fn_name == "free":
1030 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
1032 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
1033 for var in field_var_conversions:
1034 if isinstance(var, ConvInfo):
1035 if var.arg_conv_name is not None:
1036 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
1037 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
1039 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
1040 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
1042 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
1043 for suparg in var[2]:
1044 if isinstance(suparg, ConvInfo):
1045 out_c += ", " + suparg.arg_name
1047 out_c += ", " + suparg[1]
1049 out_c = out_c + "\t};\n"
1050 for var in flattened_field_var_conversions:
1051 if not isinstance(var, ConvInfo):
1052 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[2] + ".this_arg;\n"
1053 out_c = out_c + "\treturn ret;\n"
1054 out_c = out_c + "}\n"
1056 out_c = out_c + self.c_fn_ty_pfx + "uint64_t " + self.c_fn_name_define_pfx(struct_name + "_new", True) + "int32_t o"
1057 for var in flattened_field_var_conversions:
1058 if isinstance(var, ConvInfo):
1059 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1061 out_c = out_c + ", int32_t " + var[1]
1062 out_c = out_c + ") {\n"
1063 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
1064 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
1065 for var in flattened_field_var_conversions:
1066 if isinstance(var, ConvInfo):
1067 out_c = out_c + ", " + var.arg_name
1069 out_c = out_c + ", " + var[1]
1070 out_c = out_c + ");\n"
1071 out_c = out_c + "\treturn tag_ptr(res_ptr, true);\n"
1072 out_c = out_c + "}\n"
1074 return (out_typescript_bindings, out_typescript_human, out_c)
1076 def trait_struct_inc_refcnt(self, ty_info):
1077 base_conv = "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
1078 base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
1079 base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_cloned(&" + ty_info.var_name + "_conv);\n}"
1082 def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
1083 bindings_type = struct_name.replace("LDK", "")
1084 java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
1090 out_java_enum += (self.hu_struct_file_prefix)
1092 java_hu_class = "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
1093 java_hu_class += "public class " + java_hu_type + " : CommonBase {\n"
1094 java_hu_class += f"\tprotected {java_hu_type}(object _dummy, long ptr) : base(ptr)" + " { }\n"
1095 java_hu_class += "\t~" + java_hu_type + "() {\n"
1096 java_hu_class += "\t\tif (ptr != 0) { bindings." + bindings_type + "_free(ptr); }\n"
1097 java_hu_class += "\t}\n\n"
1098 java_hu_class += f"\tinternal static {java_hu_type} constr_from_ptr(long ptr) {{\n"
1099 java_hu_class += f"\t\tlong raw_ty = bindings." + struct_name + "_ty_from_ptr(ptr);\n"
1100 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"
1101 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
1102 out_c += "\tswitch(obj->tag) {\n"
1103 java_hu_class += "\t\tswitch (raw_ty) {\n"
1104 java_hu_subclasses = ""
1107 for var in variant_list:
1108 java_hu_subclasses += "\t/** A " + java_hu_type + " of type " + var.var_name + " */\n"
1109 java_hu_subclasses += "\tpublic class " + java_hu_type + "_" + var.var_name + " : " + java_hu_type + " {\n"
1110 java_hu_class += f"\t\t\tcase {var_idx}: "
1111 java_hu_class += "return new " + java_hu_type + "_" + var.var_name + "(ptr);\n"
1112 out_c += f"\t\tcase {struct_name}_{var.var_name}: return {var_idx};\n"
1114 for idx, (field_ty, field_docs) in enumerate(var.fields):
1115 if field_docs is not None:
1116 java_hu_subclasses += "\t\t/**\n\t\t * " + field_docs.replace("\n", "\n\t\t * ") + "\n\t\t */\n"
1117 java_hu_subclasses += f"\t\tpublic {field_ty.java_hu_ty} {field_ty.arg_name};\n"
1118 if field_ty.to_hu_conv is not None:
1119 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"
1120 hu_conv_body += f"\t\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1121 hu_conv_body += f"\t\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1123 hu_conv_body += f"\t\t\tthis.{field_ty.arg_name} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1124 java_hu_subclasses += "\t\tinternal " + java_hu_type + "_" + var.var_name + "(long ptr) : base(null, ptr) {\n"
1125 java_hu_subclasses += hu_conv_body
1126 java_hu_subclasses += "\t\t}\n\t}\n"
1128 java_hu_class += "\t\t\tdefault:\n\t\t\t\tthrow new ArgumentException(\"Impossible enum variant\");\n\t\t}\n\t}\n\n"
1129 out_java += self.native_meth_decl(struct_name + "_ty_from_ptr", "long") + "(long ptr);\n"
1130 out_c += ("\t\tdefault: abort();\n")
1131 out_c += ("\t}\n}\n")
1133 for var in variant_list:
1134 for idx, (field_map, _) in enumerate(var.fields):
1135 fn_name = f"{struct_name}_{var.var_name}_get_{field_map.arg_name}"
1136 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"
1137 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
1138 out_c += f"\tCHECK(obj->tag == {struct_name}_{var.var_name});\n"
1139 if field_map.ret_conv is not None:
1140 out_c += ("\t" + field_map.ret_conv[0].replace("\n", "\n\t"))
1141 if var.tuple_variant:
1142 out_c += "obj->" + camel_to_snake(var.var_name)
1144 out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
1145 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1146 out_c += "\treturn " + field_map.ret_conv_name + ";\n"
1148 if var.tuple_variant:
1149 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + ";\n"
1151 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name + ";\n"
1153 out_java += self.native_meth_decl(fn_name, field_map.java_ty) + "(long ptr);\n"
1154 out_java_enum += java_hu_class
1155 out_java_enum += java_hu_subclasses
1156 return (out_java, out_java_enum, out_c)
1158 def map_opaque_struct(self, struct_name, struct_doc_comment):
1159 out_opaque_struct_human = ""
1160 out_opaque_struct_human += self.hu_struct_file_prefix
1161 out_opaque_struct_human += "\n/**\n * " + struct_doc_comment.replace("\n", "\n * ") + "\n */\n"
1162 hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
1163 out_opaque_struct_human += ("public class " + hu_name + " : CommonBase")
1164 if struct_name.startswith("LDKLocked") or struct_name.startswith("LDKReadOnly"):
1165 out_opaque_struct_human += (", IDisposable")
1166 out_opaque_struct_human += (" {\n")
1167 out_opaque_struct_human += ("\tinternal " + hu_name + "(object _dummy, long ptr) : base(ptr) { }\n")
1168 if struct_name.startswith("LDKLocked") or struct_name.startswith("LDKReadOnly"):
1169 out_opaque_struct_human += ("\tpublic void Dispose() {\n")
1171 out_opaque_struct_human += ("\t~" + hu_name + "() {\n")
1172 out_opaque_struct_human += ("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n")
1173 out_opaque_struct_human += ("\t}\n\n")
1174 return out_opaque_struct_human
1176 def map_tuple(self, struct_name):
1177 return self.map_opaque_struct(struct_name, "A Tuple")
1179 def map_result(self, struct_name, res_map, err_map):
1180 human_ty = struct_name.replace("LDKCResult", "Result")
1182 java_hu_struct += self.hu_struct_file_prefix
1183 java_hu_struct += "public class " + human_ty + " : CommonBase {\n"
1184 java_hu_struct += "\t" + human_ty + "(object _dummy, long ptr) : base(ptr) { }\n"
1185 java_hu_struct += "\t~" + human_ty + "() {\n"
1186 java_hu_struct += "\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n"
1187 java_hu_struct += "\t}\n\n"
1188 java_hu_struct += "\tinternal static " + human_ty + " constr_from_ptr(long ptr) {\n"
1189 java_hu_struct += "\t\tif (bindings." + struct_name.replace("LDK", "") + "_is_ok(ptr)) {\n"
1190 java_hu_struct += "\t\t\treturn new " + human_ty + "_OK(null, ptr);\n"
1191 java_hu_struct += "\t\t} else {\n"
1192 java_hu_struct += "\t\t\treturn new " + human_ty + "_Err(null, ptr);\n"
1193 java_hu_struct += "\t\t}\n"
1194 java_hu_struct += "\t}\n"
1196 java_hu_struct += "\tpublic class " + human_ty + "_OK : " + human_ty + " {\n"
1198 if res_map.java_hu_ty != "void":
1199 java_hu_struct += "\t\tpublic readonly " + res_map.java_hu_ty + " res;\n"
1200 java_hu_struct += "\t\tinternal " + human_ty + "_OK(object _dummy, long ptr) : base(_dummy, ptr) {\n"
1201 if res_map.java_hu_ty == "void":
1203 elif res_map.to_hu_conv is not None:
1204 java_hu_struct += "\t\t\t" + res_map.java_ty + " res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1205 java_hu_struct += "\t\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t\t")
1206 java_hu_struct += "\n\t\t\tthis.res = " + res_map.to_hu_conv_name + ";\n"
1208 java_hu_struct += "\t\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1209 java_hu_struct += "\t\t}\n"
1210 java_hu_struct += "\t}\n\n"
1212 java_hu_struct += "\tpublic class " + human_ty + "_Err : " + human_ty + " {\n"
1213 if err_map.java_hu_ty != "void":
1214 java_hu_struct += "\t\tpublic readonly " + err_map.java_hu_ty + " err;\n"
1215 java_hu_struct += "\t\tinternal " + human_ty + "_Err(object _dummy, long ptr) : base(_dummy, ptr) {\n"
1216 if err_map.java_hu_ty == "void":
1218 elif err_map.to_hu_conv is not None:
1219 java_hu_struct += "\t\t\t" + err_map.java_ty + " err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1220 java_hu_struct += "\t\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t\t")
1221 java_hu_struct += "\n\t\t\tthis.err = " + err_map.to_hu_conv_name + ";\n"
1223 java_hu_struct += "\t\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1224 java_hu_struct += "\t\t}\n"
1226 java_hu_struct += "\t}\n\n"
1227 return java_hu_struct
1229 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):
1232 out_java_struct = None
1234 out_java += self.native_meth_decl(method_name, return_type_info.java_ty) + "("
1235 out_c += (return_type_info.c_ty)
1236 if return_type_info.ret_conv is not None:
1237 ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1238 have_args = len(argument_types) > 1 or (len(argument_types) > 0 and argument_types[0].c_ty != "void")
1239 out_c += (" " + self.c_fn_name_define_pfx(method_name, have_args))
1241 for idx, arg_conv_info in enumerate(argument_types):
1245 if arg_conv_info.c_ty != "void":
1246 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1247 out_java += (arg_conv_info.java_ty + " _" + arg_conv_info.arg_name) # Add a _ to avoid using reserved words
1249 out_java_struct = ""
1250 extra_java_struct_out = ""
1252 out_java_struct += ("\t// Skipped " + method_name + "\n")
1254 if doc_comment is not None:
1255 out_java_struct += "\t/**\n\t * " + doc_comment.replace("\n", "\n\t * ") + "\n\t */\n"
1256 hu_ret_ty = return_type_info.java_hu_ty
1257 if return_type_info.nullable:
1258 #hu_ret_ty += "?" - apparently mono doesn't support the nullable stuff
1262 out_java_struct += "\tpublic static " + hu_ret_ty + " of("
1263 elif meth_n == "default":
1264 out_java_struct += "\tpublic static " + hu_ret_ty + " with_default("
1266 out_java_struct += "\tpublic static " + hu_ret_ty + " " + meth_n + "("
1267 elif meth_n == "clone_ptr" or (struct_meth.startswith("LDKCResult") and (meth_n == "get_ok" or meth_n == "get_err")):
1268 out_java_struct += "\tinternal " + hu_ret_ty + " " + meth_n + "("
1270 if meth_n == "hash" and return_type_info.java_hu_ty == "long":
1271 extra_java_struct_out = "\tpublic override int GetHashCode() {\n"
1272 extra_java_struct_out += "\t\treturn (int)this.hash();\n"
1273 extra_java_struct_out += "\t}\n"
1274 elif meth_n == "eq" and return_type_info.java_hu_ty == "bool":
1275 extra_java_struct_out = "\tpublic override bool Equals(object o) {\n"
1276 extra_java_struct_out += "\t\tif (!(o is " + struct_meth + ")) return false;\n"
1277 extra_java_struct_out += "\t\treturn this.eq((" + struct_meth + ")o);\n"
1278 extra_java_struct_out += "\t}\n"
1279 if meth_n == "lock":
1280 out_java_struct += "\tpublic " + hu_ret_ty + " do_lock("
1282 out_java_struct += "\tpublic " + hu_ret_ty + " " + meth_n + "("
1283 for idx, arg in enumerate(argument_types):
1285 if not takes_self or idx > 1:
1286 out_java_struct += ", "
1289 if arg.java_ty != "void":
1290 if arg.arg_name in default_constructor_args:
1291 assert not arg.nullable
1292 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1293 if explode_idx != 0:
1294 out_java_struct += (", ")
1295 out_java_struct += (
1296 explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
1298 ty_string = arg.java_hu_ty
1300 #ty_string += "?" - apparently mono doesn't support the nullable stuff
1302 ty_string = self.fully_qualified_hu_ty_path(arg)
1303 out_java_struct += ty_string + " " + arg_name_repl(arg.arg_name, arg.arg_name)
1304 out_java += (");\n")
1306 if out_java_struct is not None:
1307 out_java_struct += (") {\n")
1308 for info in argument_types:
1309 if info.arg_conv is not None:
1310 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1311 if return_type_info.ret_conv is not None:
1312 out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1313 elif return_type_info.c_ty != "void":
1314 out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1317 if c_call_string is None:
1318 out_c += (method_name + "(")
1320 out_c += (c_call_string)
1321 for idx, info in enumerate(argument_types):
1322 if info.arg_conv_name is not None:
1325 elif c_call_string is not None:
1327 out_c += (info.arg_conv_name)
1329 if return_type_info.ret_conv is not None:
1330 out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1333 for info in argument_types:
1334 if info.arg_conv_cleanup is not None:
1335 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1336 if return_type_info.ret_conv is not None:
1337 out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1338 elif return_type_info.c_ty != "void":
1339 out_c += ("\n\treturn ret_val;")
1340 out_c += ("\n}\n\n")
1343 out_java_struct += ("\t\t")
1344 if return_type_info.java_ty != "void":
1345 out_java_struct += (return_type_info.java_ty + " ret = ")
1346 out_java_struct += ("bindings." + method_name + "(")
1347 for idx, info in enumerate(argument_types):
1349 out_java_struct += (", ")
1350 if idx == 0 and takes_self:
1351 out_java_struct += ("this.ptr")
1352 elif info.arg_name in default_constructor_args:
1353 out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1354 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1355 if explode_idx != 0:
1356 out_java_struct += (", ")
1357 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1358 if explode_arg.from_hu_conv is not None:
1359 out_java_struct += (
1360 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1362 out_java_struct += (expl_arg_name)
1363 out_java_struct += (")")
1364 elif info.from_hu_conv is not None:
1365 out_java_struct += arg_name_repl(info.from_hu_conv[0], info.arg_name)
1367 out_java_struct += arg_name_repl(info.arg_name, info.arg_name)
1368 out_java_struct += (");\n")
1370 # Like Java, the C# GC is quite aggressive and can finalize an object while a method
1371 # on it is operating. Unlike Java, this behavior appears to be better documented,
1373 for idx, info in enumerate(argument_types):
1374 if idx == 0 and takes_self:
1375 out_java_struct += ("\t\tGC.KeepAlive(this);\n")
1376 elif info.arg_name in default_constructor_args:
1377 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1378 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1379 out_java_struct += ("\t\tGC.KeepAlive(" + expl_arg_name + ");\n")
1380 elif info.c_ty != "void":
1381 out_java_struct += ("\t\tGC.KeepAlive(" + arg_name_repl(info.arg_name, info.arg_name) + ");\n")
1383 if return_type_info.java_ty == "long" and return_type_info.java_hu_ty != "long":
1384 out_java_struct += "\t\tif (ret >= 0 && ret <= 4096) { return null; }\n"
1386 if return_type_info.to_hu_conv is not None:
1388 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t")
1389 .replace("this", return_type_info.to_hu_conv_name) + "\n")
1391 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1393 for idx, info in enumerate(argument_types):
1394 if idx == 0 and takes_self:
1396 elif info.arg_name in default_constructor_args:
1397 for explode_arg in default_constructor_args[info.arg_name]:
1398 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1399 if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1400 out_java_struct += ("\t\t" +
1401 arg_name_repl(explode_arg.from_hu_conv[1], info.arg_name)
1402 .replace(explode_arg.arg_name, expl_arg_name)
1403 .replace("this", return_type_info.to_hu_conv_name) + ";\n")
1404 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1405 if not takes_self and return_type_info.to_hu_conv_name is not None:
1406 out_java_struct += ("\t\t" + arg_name_repl(info.from_hu_conv[1], info.arg_name)
1407 .replace("this", return_type_info.to_hu_conv_name)
1408 .replace("\n", "\n\t\t") + ";\n")
1410 out_java_struct += ("\t\t" + arg_name_repl(info.from_hu_conv[1], info.arg_name)
1411 .replace("\n", "\n\t\t") + ";\n")
1413 if takes_self and not takes_self_as_ref:
1414 out_java_struct += "\t\t" + argument_types[0].from_hu_conv[1].replace("\n", "\n\t\t").replace("this_arg", "this") + ";\n"
1415 if return_type_info.to_hu_conv_name is not None:
1416 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1417 elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1418 out_java_struct += ("\t\treturn ret;\n")
1419 out_java_struct += ("\t}\n\n")
1421 return (out_java, out_c, out_java_struct + extra_java_struct_out)
1424 with open(self.outdir + "src/org/ldk/impl/bindings.cs", "a") as bindings:
1425 for fn_suffix in self.function_ptrs:
1426 jret = self.function_ptrs[fn_suffix]["ret"][0]
1427 jargs = self.function_ptrs[fn_suffix]["args"][0]
1430 static {jret} c_callback_{fn_suffix}(int obj_ptr, int fn_id{jargs}) {{
1431 if (obj_ptr >= js_objs.Count) {{
1432 Console.Error.WriteLine("Got function call on unknown/free'd JS object in {fn_suffix}");
1433 Console.Error.Flush();
1434 Environment.Exit(42);
1436 object obj = js_objs[obj_ptr].Target;
1438 Console.Error.WriteLine("Got function call on GC'd JS object in {fn_suffix}");
1439 Console.Error.Flush();
1440 Environment.Exit(43);
1443 bindings.write("\t\tswitch (fn_id) {\n")
1444 for f in self.function_ptrs[fn_suffix]:
1445 if f != "ret" and f != "args" and f != "call":
1446 bindings.write(f"""\t\t\tcase {str(f)}:
1447 if (!(obj is {self.function_ptrs[fn_suffix][f][0]})) {{
1448 Console.Error.WriteLine("Got function call to object that wasn't a {self.function_ptrs[fn_suffix][f][0]} in {fn_suffix}");
1449 Console.Error.Flush();
1450 Environment.Exit(44);
1452 call = f"(({self.function_ptrs[fn_suffix][f][0]})obj).{self.function_ptrs[fn_suffix][f][1]}({self.function_ptrs[fn_suffix][f][2]});"
1454 bindings.write("\t\t\t\treturn " + call)
1456 bindings.write("\t\t\t\t" + call + "\n\t\t\t\treturn;")
1457 bindings.write("\n")
1459 bindings.write(f"""\t\t\tdefault:
1460 Console.Error.WriteLine("Got unknown function call with id " + fn_id + " from C in {fn_suffix}");
1461 Console.Error.Flush();
1462 Environment.Exit(45);
1463 return{" false" if jret == "bool" else " 0" if jret != "void" else ""};
1466 public delegate {jret} {fn_suffix}_callback(int obj_ptr, int fn_id{jargs});
1467 static {fn_suffix}_callback {fn_suffix}_callback_inst = c_callback_{fn_suffix};
1469 bindings.write(self.native_meth_decl(f"register_{fn_suffix}_invoker", "int") + f"({fn_suffix}_callback callee);\n")
1470 # Easiest way to get a static run is just define a variable, even if we dont care
1471 bindings.write(f"\tstatic int _run_{fn_suffix}_registration = register_{fn_suffix}_invoker({fn_suffix}_callback_inst);")