Skip to content

Instantly share code, notes, and snippets.

@stefanhuber
Created December 13, 2021 10:15
Show Gist options
  • Select an option

  • Save stefanhuber/ca1bbe954b60fd35f68366b827c60dbc to your computer and use it in GitHub Desktop.

Select an option

Save stefanhuber/ca1bbe954b60fd35f68366b827c60dbc to your computer and use it in GitHub Desktop.

Revisions

  1. stefanhuber created this gist Dec 13, 2021.
    1 change: 1 addition & 0 deletions command
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    Module._free(arrayPointer);emcc C:\00_projects\wasm-experiment\main.c -o C:\00_projects\wasm-experiment\www\sort.html -s NO_EXIT_RUNTIME=1 -s "EXPORTED_RUNTIME_METHODS=['ccall','cwrap']" -s "EXPORTED_FUNCTIONS=['_malloc','_free']"
    13 changes: 13 additions & 0 deletions glue.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    const items = [-12, 4, 0, 2];
    const arrayLength = items.length;
    const bytesPerElement = Module.HEAP32.BYTES_PER_ELEMENT;

    const arrayPointer = Module._malloc((arrayLength * bytesPerElement));

    Module.HEAP32.set(items, (arrayPointer / bytesPerElement));

    Module.ccall('selection_sort',
    null,
    ['number', 'number'],
    [arrayPointer, arrayLength]
    );
    24 changes: 24 additions & 0 deletions main.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    #include <stdio.h>
    #include <emscripten.h>

    EMSCRIPTEN_KEEPALIVE void selection_sort (int *a, int n) {
    int i, j, m, t;

    for (i = 0; i < n; i++)
    printf("%d%s", a[i], i == n - 1 ? "\n" : " ");


    for (i = 0; i < n; i++) {
    for (j = i, m = i; j < n; j++) {
    if (a[j] < a[m]) {
    m = j;
    }
    }
    t = a[i];
    a[i] = a[m];
    a[m] = t;
    }

    for (i = 0; i < n; i++)
    printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
    }