Possibly the worst way to encode json in C?
% emcc example.c -o example.js -s DEFAULT_LIBRARY_FUNCS_TO_INCLUDE='$UTF8ToString,$stringToNewUTF8
% node example.js
JSON: {"name":"Captain Pants","id":0}
| // Compile with emcc -s DEFAULT_LIBRARY_FUNCS_TO_INCLUDE='$UTF8ToString,$stringToNewUTF8' | |
| #include <stdio.h> | |
| #include <emscripten.h> | |
| int main() { | |
| struct player { | |
| char *name; | |
| int id; | |
| } foo; | |
| foo.name = "Captain Pants"; | |
| foo.id = 0; | |
| // Use JavaScript's JSON.stringify() to generate JSON into a char* for use in C. | |
| const char *json = (const char *)EM_ASM_PTR({ | |
| return stringToNewUTF8(JSON.stringify({ | |
| name: UTF8ToString($0), | |
| id: $1 | |
| })); | |
| }, foo.name, foo.id); | |
| printf("JSON: %s\n", json); | |
| free((void *)json); | |
| return 0; | |
| } |