DEV Community

kyorohiro (kiyohiro kawamura)
kyorohiro (kiyohiro kawamura)

Posted on • Updated on

Dart and C : how to ffi and wasm (2) Hello

Let's create the Shared Library and JS Library in the environment we created last time.

Create a C language function that displays "Hello !!" and call that function at "Web browser" and "Linux Server".

Create Clang func

#include <stdio.h>

// [Linux]
// find . -name "*.o" | xargs rm
// gcc -Wall -Werror -fpic -I. -c ky.c -o ky.o 
// gcc -shared -o libky.so ky.o

// [Wasm]
// find . -name "*.o" | xargs rm
// find . -name "*.wasm" | xargs rm
// emcc ky.c -o ky.o 
// emcc ky.o -o libky.js -s EXTRA_EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]' -s EXPORTED_FUNCTIONS="['_print_hello']"
// cp libky.js ../web/libky.js 
// cp libky.wasm ../web/libky.wasm
void print_hello() {
    printf("Hello!!\n");
}
Enter fullscreen mode Exit fullscreen mode

Create Shared Library

$ find . -name "*.o" | xargs rm
$ gcc -Wall -Werror -fpic -I. -c ky.c -o ky.o 
$ gcc -shared -o libky.so ky.o
Enter fullscreen mode Exit fullscreen mode

Create JS and WASM

$ find . -name "*.o" | xargs rm
$ find . -name "*.wasm" | xargs rm
$ emcc ky.c -o ky.o 
$ emcc ky.o -o libky.js -s EXTRA_EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]' -s EXPORTED_FUNCTIONS="['_print_hello']"
Enter fullscreen mode Exit fullscreen mode

Let's call this function from linux server

import 'dart:ffi' as ffi;

typedef PrintHelloFunc = ffi.Pointer<ffi.Void> Function();
typedef PrintHello = ffi.Pointer<ffi.Void> Function();

ffi.DynamicLibrary dylib = ffi.DynamicLibrary.open('/app/libc/libky.so');
PrintHello _print_hello = dylib
    .lookup<ffi.NativeFunction<PrintHelloFunc>>('print_hello')
    .asFunction();

void printHello() {
  _print_hello();
}

main(List<String> args) {
  printHello();
}
Enter fullscreen mode Exit fullscreen mode

Let's call this function from Web Browser

import 'dart:js' as js;

js.JsObject Module = js.context['Module'];
js.JsFunction _print_hello =  Module.callMethod('cwrap',['print_hello','',[]]);

void printHello() {
  _print_hello.apply([]);
}

void main() {  
  printHello();
}


Enter fullscreen mode Exit fullscreen mode

Test

$ dart ./bin/main.dart 
Enter fullscreen mode Exit fullscreen mode
webdev serve --hostname=0.0.0.0
Enter fullscreen mode Exit fullscreen mode

thanks!!

Next time

I will explain how to handle Buffer OR how to handle various Primitives.

PS

this text's code is the following
https://github.com/kyorohiro/dart_clang_codeserver/tree/02_hello

Top comments (1)

Collapse
 
tonku profile image
Tony Thomas

Awesome