#include #include #include "utils/log.h" #include "wrt/dl.h" #include "wrt/wrt.h" uint8_t *read_file(const char *filename, uint32_t *fsize) { FILE *f = fopen(filename, "rb"); if (f == NULL) { LOG_ERR("read_file: fopen failed"); return NULL; } fseek(f, 0, SEEK_END); *fsize = ftell(f); fseek(f, 0, SEEK_SET); // same as rewind(f); uint8_t *buffer = malloc(*fsize + 1); fread(buffer, *fsize, 1, f); fclose(f); buffer[*fsize] = 0; return buffer; } void test_wrt() { uint32_t buf_size; uint8_t *buf = read_file("example.wasm", &buf_size); WRTContext context; wrt_platform_init(&context, malloc, free); wrt_mem_init(&context, 512 * 1024, 128); wrt_program_init(&context, buf, buf_size, NULL, 0); wrt_wamr_init(&context, "entry", 8092, 8092); wrt_run(&context); wrt_free(&context); free(buf); } unsigned char foo(unsigned int x, float y, char z, double w) { printf("foo: x=%u, y=%f, z=%c, w=%lf\n", x, y, z, w); return 'P'; } void test_ffi() { ffi_cif cif; ffi_type *arg_types[4]; void *arg_values[4]; ffi_status status; // Because the return value from foo() is smaller than sizeof(long), it // must be passed as ffi_arg or ffi_sarg. ffi_arg result; // Specify the data type of each argument. Available types are defined // in . arg_types[0] = &ffi_type_uint; arg_types[1] = &ffi_type_float; arg_types[2] = &ffi_type_schar; arg_types[3] = &ffi_type_double; // Prepare the ffi_cif structure. if ((status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &ffi_type_uint8, arg_types)) != FFI_OK) { // Handle the ffi_status error. LOG_ERR("ffi_prep_cif failed: %d", status); } // Specify the values of each argument. unsigned int arg1 = 42; float arg2 = 5.1f; char arg3 = 'A'; double arg4 = 114.1514; arg_values[0] = &arg1; arg_values[1] = &arg2; arg_values[2] = &arg3; arg_values[3] = &arg4; // Invoke the function. ffi_call(&cif, FFI_FN(foo), &result, arg_values); // The ffi_arg 'result' now contains the unsigned char returned from foo(), // which can be accessed by a typecast. printf("result is %c\n", (unsigned char)result); } int main() { LOG_INFO("WRT Test"); test_ffi(); test_wrt(); return 0; }