From 1cc48a370af3886c7a3eefb46d00b57a0d4c9161 Mon Sep 17 00:00:00 2001 From: Calvin Rose Date: Fri, 10 Jun 2022 08:46:20 -0500 Subject: [PATCH] Add native-write, which will write structs to buffers. Useful for testing as well as useful in its own right. Begs for an inverse, native-read which would convert byte data to native structs. --- src/core/ffi.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/core/ffi.c b/src/core/ffi.c index f6306b98..10c152bc 100644 --- a/src/core/ffi.c +++ b/src/core/ffi.c @@ -641,11 +641,28 @@ JANET_CORE_FN(cfun_ffi_call, } } +JANET_CORE_FN(cfun_ffi_buffer_write, + "(native-write ffi-type data &opt buffer)", + "Append a native tyep to a buffer such as it would appear in memory. This can be used " + "to pass pointers to structs in the ffi, or send C/C++/native structs over the network " + "or to files. Returns a modifed buffer or a new buffer if one is not supplied.") { + janet_arity(argc, 2, 3); + JanetFFIType type = decode_ffi_type(argv[0]); + size_t el_size = type_size(type); + JanetBuffer *buffer = janet_optbuffer(argv, argc, 2, el_size); + janet_buffer_extra(buffer, el_size); + memset(buffer->data, 0, el_size); + janet_ffi_write_one(buffer->data, argv, 1, type); + buffer->count += el_size; + return janet_wrap_buffer(buffer); +} + void janet_lib_ffi(JanetTable *env) { JanetRegExt ffi_cfuns[] = { JANET_CORE_REG("native-signature", cfun_ffi_signature), JANET_CORE_REG("native-call", cfun_ffi_call), JANET_CORE_REG("native-struct", cfun_ffi_struct), + JANET_CORE_REG("native-write", cfun_ffi_buffer_write), JANET_REG_END }; janet_core_cfuns_ext(env, NULL, ffi_cfuns);