This repository has been archived on 2023-11-05. You can view files and clone it, but cannot push or open issues or pull requests.
wrt/main.c

97 lines
2.4 KiB
C
Raw Normal View History

2023-02-06 21:03:06 +08:00
#include <stdio.h>
#include <stdlib.h>
#include "utils/log.h"
#include "wrt/dl.h"
#include "wrt/wrt.h"
2023-02-07 11:17:51 +08:00
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;
}
2023-02-06 21:03:06 +08:00
void test_wrt() {
2023-02-07 11:17:51 +08:00
uint32_t buf_size;
2023-02-07 11:22:47 +08:00
uint8_t *buf = read_file("example.wasm", &buf_size);
2023-02-07 11:17:51 +08:00
2023-02-06 21:03:06 +08:00
WRTContext context;
wrt_platform_init(&context, malloc, free);
wrt_mem_init(&context, 512 * 1024, 128);
2023-02-07 11:17:51 +08:00
wrt_program_init(&context, buf, buf_size, NULL, 0);
2023-02-06 21:03:06 +08:00
wrt_wamr_init(&context, "entry", 8092, 8092);
wrt_run(&context);
wrt_free(&context);
2023-02-07 11:17:51 +08:00
free(buf);
2023-02-06 21:03:06 +08:00
}
2023-02-07 23:19:28 +08:00
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 <ffi/ffi.h>.
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);
}
2023-02-06 21:03:06 +08:00
int main() {
2023-02-07 11:17:51 +08:00
LOG_INFO("WRT Test");
2023-02-07 23:19:28 +08:00
test_ffi();
2023-02-07 11:17:51 +08:00
test_wrt();
2023-02-06 21:03:06 +08:00
return 0;
}