If the  js_string_to_c_string() function is only called from that one place 
I would put it right into the em_enumerate_av_devices() function as a local 
function similar to what I do here:

https://github.com/floooh/sokol/blob/be081ef0487017d85e03cd8f526dace502551d9e/sokol_audio.h#L1729-L1739

To pass a JS string to a C function you can use the automatic marshalling 
in the ccall() helper function. For instance here I'm getting a JS string 
from the clipboard and pass it to a C function:

https://github.com/floooh/sokol/blob/be081ef0487017d85e03cd8f526dace502551d9e/sokol_app.h#L4047-L4053

...and the C function simply looks like this (make sure to copy the string 
data, because AFAIK the original data will be freed after the C function 
returns:

https://github.com/floooh/sokol/blob/be081ef0487017d85e03cd8f526dace502551d9e/sokol_app.h#L3928-L3936

On Saturday, 22 May 2021 at 20:42:36 UTC+2 [email protected] wrote:

> I'm quite new to combining C and JavaScript and I'm having trouble seeing 
> how I can possibly access a string in C (on the WASM heap) made as a result 
> of a promise. Here's the function I have so far:
>
> EM_JS(void, em_enumerate_av_devices, (),
> {
> navigator.mediaDevices.enumerateDevices()
> .then(function(devices) {
> var str="";
> devices.forEach( function(device) { str += device.kind + " \"" + 
> device.label + "\" id = " + device.deviceId + "\n"; });
> var c_str = js_string_to_c_string(str); // this is the C string on the 
> WASM heap I'm trying to access in C, I don't know what to do with it
> })
> .catch(function(err) { console.log(err.name + ": " + err.message); });
> });
>
> I need c_str to somehow be accessed from my C code, but how?
>
> Another smaller problem is the function it relies on, 
> js_string_to_c_string(), which is as follows:
>
> function js_string_to_c_string(js_string)
> {
> var len = lengthBytesUTF8(js_string) + 1;
> var c_string = _malloc(len);
> stringToUTF8(js_string, c_string, len);
> return c_string;
> }
>
> I tried putting the whole thing inside an EM_ASM block, but the compiler 
> didn't like that and I haven't seen anyone else use EM_ASM for entire 
> functions. It would make sense to put such utility functions in one .js 
> file, but I can't see how to make emcc include that .js file anywhere 
> (ideally it would include the whole thing into myproject.js like it already 
> does with required files such as runtime_safe_heap.js and others).
>
> Thanks in advance,
>
> Michel Rouzic
>

-- 
You received this message because you are subscribed to the Google Groups 
"emscripten-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/emscripten-discuss/0bdac1f9-62a9-4395-9ce1-f2e3863515f7n%40googlegroups.com.

Reply via email to