WebAssembly01--c代码调用js

编译选项

 emcc test.c --js-library pkg.js -o test.js

pkg.js

mergeInto(LibraryManager.library,{
    js_add:function(a,b) {
        console.log("js_add");
        return a+b;
    },
    js_console_log_int:function(param){
        console.log("js_console_log_in:"+param);
    }
})

test.c

#ifndef EM_PORT_API
#	if defined(__EMSCRIPTEN__)
#		include <emscripten.h>
#		if defined(__cplusplus)
#			define EM_PORT_API(rettype) extern "C" rettype EMSCRIPTEN_KEEPALIVE
#		else
#			define EM_PORT_API(rettype) rettype EMSCRIPTEN_KEEPALIVE
#		endif
#	else
#		if defined(__cplusplus)
#			define EM_PORT_API(rettype) extern "C" rettype
#		else
#			define EM_PORT_API(rettype) rettype
#		endif
#	endif
#endif

#include<stdio.h>
#include<emscripten.h>
#include<stdlib.h>
#include<string.h>
EM_PORT_API(int) js_add(int a,int b);
EM_PORT_API(void) js_console_log_int(int param);
EM_PORT_API(void) print_the_answer(){
	int i=js_add(21,21);
	js_console_log_int(i);
}


EM_PORT_API(char*) str_merge(char* str1,char* str2)
{
	int str1_len = 0;
	int str2_len = 0;
	int size = 0;
	char *buf = NULL;
	if(str1) str1_len = strlen(str1);
	if(str2) str2_len = strlen(str2);
	size = str1_len+str2_len;
	buf = (char*)malloc(size);
	memset(buf,0,size);
	if(str1_len>0)strncpy(buf,str1,str1_len);
	if(str2_len>0)strncpy(buf+str1_len,str2,str2_len);
	return buf;//return merge result
}
EM_PORT_API(int) add(int a,int b)
{
	return a+b;
}
int main(int argc,char** argv)
{
	return add(1,2);	
	
}


<html>
	<head>
		<title>test page</title>

	</head>
	<body>
		<script >
		Module={}
		Module.onRuntimeInitialized=function(){
			Module._print_the_answer();
		}
	
		</script>
		<script src="test.js"></script>
	</body>
</html>

emrun --no_browser --port 8000 test.html
posted @ 2022-10-12 09:23  simp00  阅读(101)  评论(0编辑  收藏  举报