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.
wasm-micro-runtime/samples/native-lib
YAMAMOTO Takashi 654ac5feca
Use cmake POSITION_INDEPENDENT_CODE instead of hardcoding -pie -fPIE (#1598)
This fixes unused option warnings on -pie for macOS.
(On macOS cmake produces "-fPIE -Xlinker -pie")

Bump required cmake version to 3.14 for CheckPIESupported.

References:
https://cmake.org/cmake/help/latest/prop_tgt/POSITION_INDEPENDENT_CODE.html
https://cmake.org/cmake/help/latest/module/CheckPIESupported.html#module:CheckPIESupported
2022-10-19 01:51:18 +08:00
..
wasm-app Enable register native with iwasm (#1120) 2022-04-27 11:12:50 +08:00
CMakeLists.txt Use cmake POSITION_INDEPENDENT_CODE instead of hardcoding -pie -fPIE (#1598) 2022-10-19 01:51:18 +08:00
README.md Fix the "register native with iwasm" stuff for macOS (#1558) 2022-10-07 15:17:36 +08:00
test_add.c samples/native-lib: Fix exec_env type (#1557) 2022-10-06 20:21:21 +08:00
test_sqrt.c samples/native-lib: Fix exec_env type (#1557) 2022-10-06 20:21:21 +08:00

"native-lib" sample introduction

This sample demonstrates how to write required interfaces in native library, build it into a shared library and register the shared library to iwasm.

The native library should provide get_native_lib API for iwasm to return the native library info, including the module name, the native symbol list and the native symbol count, so that iwasm can use them to regiter the native library, for example:

static int
foo_wrapper(wasm_exec_env_t exec_env, int x, int y)
{
    return x + y;
}

#define REG_NATIVE_FUNC(func_name, signature) \
    { #func_name, func_name##_wrapper, signature, NULL }

static NativeSymbol native_symbols[] = {
    REG_NATIVE_FUNC(foo, "(ii)i")
};

uint32_t
get_native_lib(char **p_module_name, NativeSymbol **p_native_symbols)
{
    *p_module_name = "env";
    *p_native_symbols = native_symbols;
    return sizeof(native_symbols) / sizeof(NativeSymbol);
}

Preparation

Please install WASI SDK, download the wasi-sdk release and extract the archive to default path /opt/wasi-sdk.

Build the sample

mkdir build
cd build
cmake ..
make

iwasm, one wasm module test.wasm and two shared libraries libtest_add.so, libtest_sqrt.so will be generated.

Run workload

Linux

cd build
./iwasm --native-lib=libtest_add.so --native-lib=libtest_sqrt.so wasm-app/test.wasm

macOS

cd build
./iwasm --native-lib=libtest_add.dylib --native-lib=libtest_sqrt.dylib wasm-app/test.wasm

The output is:

Hello World!
10 + 20 = 30
sqrt(10, 20) = 500