Last active
November 30, 2021 16:25
-
-
Save kikuchan/ac33b7c85061de6f4a0d8fcb755460fd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "ffi.h" | |
STATIC mp_obj_t example_printf(size_t n_args, const mp_obj_t *args) { | |
ffi_cif cif; | |
ffi_type **types = alloca(n_args * sizeof(ffi_type *)); | |
ffi_raw *values = alloca(n_args * sizeof(ffi_raw)); | |
void **arg_values = alloca(n_args * sizeof(void *)); | |
ffi_arg result; | |
size_t i; | |
for (i = 0; i < n_args; i++) { | |
if (mp_obj_get_int_maybe(args[i], (mp_int_t *)&values[i].sint)) { | |
types[i] = &ffi_type_sint; | |
} else if (mp_obj_get_float_maybe(args[i], (mp_float_t *)&values[i].flt)) { | |
types[i] = &ffi_type_double; | |
} else if (mp_obj_is_str(args[i])) { | |
types[i] = &ffi_type_pointer; | |
values[i].ptr = (void *)mp_obj_str_get_str(args[i]); | |
} else { | |
// ERROR | |
mp_raise_TypeError(MP_ERROR_TEXT("not supported type is specified")); | |
} | |
arg_values[i] = &values[i]; | |
} | |
ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, n_args, &ffi_type_sint, types); | |
ffi_call(&cif, FFI_FN(printf), &result, arg_values); | |
return mp_obj_new_int(result); | |
} | |
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(example_printf_obj, 1, example_printf); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment