11

I would like to port a C library. There is a really short tutorial about it here: Interacting with code

I need to create a struct using javascript, and return a pointer to it. I looked into the libraries, which are already ported. My code looks like this:

var ptr = _malloc({{{ C_STRUCTS.MyStruct.__size__ }}});

{{{ makeSetValue('ptr', C_STRUCTS.MyStruct.attr, '0', 'i8') }}};

It does not work, because emscripten does not know about MyStruct.

My library definition is added to the project using --js-library But I don't know, how to add a struct definition (struct_info.json)

In the C code, I have:

struct MyStruct {
    int8_t attr;
    //...
}
Iter Ator
  • 8,226
  • 20
  • 73
  • 164
  • I don't know about emscripten but can't you create a `createMyStruct` function in C and use it? – Bryan Chen Dec 11 '16 at 22:19
  • Unfortunately this is not an option. The `MyStruct_Create` function has to be implemented in js – Iter Ator Dec 11 '16 at 22:42
  • Possible duplicate of: http://stackoverflow.com/questions/28904273/struct-operations-in-javascript-through-emscripten – Ouroborus Dec 16 '16 at 19:55
  • It is not a duplicate. I would like to access data using the emscripten macros like `makeSetValue`, and not by working on the memory buffer directly – Iter Ator Dec 16 '16 at 20:08
  • @IterAtor Let me get this straight:you would like to export your C struct right? And be able to use it from JS? Have you tried EMSCRIPTEN_BINDINGS(my_value_example) { value_array("MyStruct") .element(&MyStruct::attr) ... ? – fedepad Dec 21 '16 at 00:38
  • I guess you properly exported the struct, for example with EMSCRIPTEN_BINDINGS.... right? – fedepad Dec 21 '16 at 00:49
  • Have you already written a struct_info.json file? Maybe you can use the following: https://github.com/kripken/emscripten/blob/master/tools/gen_struct_info.py, which seems the tool emscripten itself uses to generate that kind of info either taking a raw C header file or an input json file (what they claim). The struct_info.json is used in the emscripten itself as you can see and they use the C structs it throughout the code in the way you want to use it. – fedepad Dec 21 '16 at 09:38

1 Answers1

1

You should create C but not JS struct. For example:

var st_t = new ctypes.StructType("st_t",
        [ { "self": ctypes.PointerType(ctypes.void_t) },
        { "str": ctypes.PointerType(ctypes.char) },
        { "buff_size": ctypes.size_t },
        { "i": ctypes.int },
        { "f": ctypes.float },
        { "c": ctypes.char } ]);  

Hope it will help.

MD XF
  • 7,860
  • 7
  • 40
  • 71
Y. Verzun
  • 109
  • 1
  • 7