Skip to content

Commit

Permalink
add an example to use toywasm as a library
Browse files Browse the repository at this point in the history
  • Loading branch information
yamt committed Feb 22, 2023
1 parent 57c6837 commit a1c40ec
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
17 changes: 17 additions & 0 deletions examples/app/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
cmake_minimum_required(VERSION 3.16)

project(app LANGUAGES C)

find_package(toywasm REQUIRED)

set(app_sources
"app.c"
)

add_executable(app ${app_sources})
target_link_libraries(app toywasm-lib)

# XXX the library is built with short enum.
# maybe we can use INTERFACE_COMPILE_OPTIONS.
# but i feel a bit uncomfortable with it.
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fshort-enums")
46 changes: 46 additions & 0 deletions examples/app/app.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#include <inttypes.h>
#include <stdlib.h>

#include <toywasm/fileio.h>
#include <toywasm/load_context.h>
#include <toywasm/module.h>
#include <toywasm/type.h>
#include <toywasm/xlog.h>

int
main(int argc, char **argv)
{
xlog_printf("hello\n");
if (argc != 2) {
xlog_error("unexpected number of args");
exit(2);
}
const char *filename = argv[1];

struct module *m;
int ret;
uint8_t *p;
size_t sz;
ret = map_file(filename, (void **)&p, &sz);
if (ret != 0) {
xlog_error("map_file failed with %d", ret);
exit(1);
}
ret = module_create(&m);
if (ret != 0) {
xlog_error("module_create failed with %d", ret);
exit(1);
}
struct load_context ctx;
load_context_init(&ctx);
ret = module_load(m, p, p + sz, &ctx);
if (ret != 0) {
xlog_error("module_load failed with %d", ret);
exit(1);
}
xlog_printf("module %s imports %" PRIu32 " functions\n", filename,
m->nimportedfuncs);
xlog_printf("module %s contains %" PRIu32 " functions\n", filename,
m->nfuncs);
exit(0);
}

0 comments on commit a1c40ec

Please sign in to comment.