Forked from kyorohiro/helloworld_emcc_connect_to_js_pointer.log
Created
March 22, 2020 06:14
-
-
Save Jesseyx/d331043d2a97349f1c150a571522a957 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$emacs libtest.c | |
#include <math.h> | |
#include <string.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
// | |
// int | |
int int_sqrt(int x) { | |
return sqrt(x); | |
} | |
// | |
// string | |
char* chars_hello(char* src) { | |
return strcat( "Hello ", src ); | |
} | |
// | |
// pointer | |
typedef struct { | |
char* name; | |
} Hello; | |
Hello* new_hello(char *name, int length) { | |
Hello *obj = (Hello*)calloc(1, sizeof(Hello)); | |
obj->name = (char*)calloc(1, sizeof(char)*(length+1)); | |
for(int i=0;i<length;i++) { | |
obj->name[i] = name[i]; | |
} | |
return obj; | |
} | |
char* hello_getName(Hello* obj) { | |
return obj->name; | |
} | |
void free_hello(Hello* obj) { | |
if(obj == NULL) { | |
return; | |
} | |
free(obj->name); | |
free(obj); | |
} | |
$ emcc libtest.c -o libtest.js -s EXPORTED_FUNCTIONS='["_int_sqrt","_chars_hello", "_new_hello","_hello_getName", "_hello_getName", "_free_hello"]' -s EXTRA_EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]' | |
$ emacs main.html | |
<html> | |
<head> | |
<title></title> | |
</head> | |
<body> | |
<script src="libtest.js"></script> | |
<script> | |
// | |
// int | |
int_sqrt = Module.cwrap('int_sqrt', 'number', ['number']); | |
console.log("#int_sqrt : "+int_sqrt(12)); | |
// | |
// string | |
chars_hello = Module.cwrap('chars_hello', 'string', ['string']); | |
console.log("#chars_hello : " + chars_hello('test')); | |
// | |
// uint8array | |
helloArray = []; | |
helloSrc = "hello"; | |
for(i=0;i<helloSrc.length;i++){ | |
helloArray.push(helloSrc.charCodeAt(i)); | |
} | |
hello = chars_hello(new Uint8Array('helloArray')); | |
console.log("#chars_hello : " + hello); | |
// | |
// pointer | |
new_hello = Module.cwrap('new_hello', 'number', ['string', 'number']); | |
hello_getName = Module.cwrap('hello_getName', 'string', ['number']); | |
free_hello = Module.cwrap('free_hello', '', ['number']); | |
helloObj = new_hello("test", 4); | |
console.log("#pointer:" + hello_getName(helloObj)); | |
free_hello(helloObj); | |
</script> | |
</body> | |
</html> | |
$ python -m SimpleHTTPServer | |
Serving HTTP on 0.0.0.0 port 8000 ... | |
$ open http://0.0.0.0:8000/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment