WebAssembly + C struct(구조체)

개발 이야기/WEB 2020. 5. 15. 17:32

구조체를 가져와서 출력해보는 예제.

 

1. 소스 코드 작성

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//struct_test.c
 
#include <stdio.h>
#include <emscripten/emscripten.h>
#include <stdlib.h>
 
typedef struct st_study
{
        int value_1;
        int value_2;
} study;
 
EMSCRIPTEN_KEEPALIVE
study* init_struct(int value_1st, int value_2nd)
{
        study* stStudy = (study*)malloc(sizeof(study));
 
        stStudy->value_1 = value_1st;
        stStudy->value_2 = value_2nd;
 
        return stStudy;
}
 
cs

 

2. 컴파일

 

1
emcc struct_test.c -o struct_test.js -s WASM=1 -s EXTRA_EXPORTED_RUNTIME_METHODS=['ccall','cwrap','getValue']
cs

 

3. index.html 작성

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Wasm Test Page</title>
</head>
<body>
<button id="btn" onclick="OnClickBtn();">click here!</button>
<script>
function OnClickBtn()
{
    const study = Module.ccall('init_struct',
            'number',
            ['number''number'],
            [510]);
    
    var value_1 = Module.getValue(study, 'i32');
    var value_2 = Module.getValue(study + 4'i32');
    
    console.log('[study] value_1 = ' + value_1 + ' value_2 = ' + value_2);
}
</script>
<script type='text/javascript' src='./js/struct_test.js'></script>
</body>
</html>
 
cs

 

- return type : 'number' 는 pointer 도 포함.

- getValue(ptr, type [, noSafe]) 

  ptr -> study 구조체 변수는 4바이트 2개. 처음 value_1 가 4바이트형 자료형이기 때문에 + 4.

  type -> 'i32' 4바이트 변수 자료형

  

4. 결과 확인

 

웹어셈 관련 글을 작성하고 있지만, 이게 100%는 아니다.

그냥 참고만 하시길...

'개발 이야기 > WEB' 카테고리의 다른 글

WebAssembly C++ Class Binding  (0) 2020.05.18
Eclipse Web Project + WebAssembly Sample  (0) 2020.05.12