#How to pass strings to FFI

1 messages · Page 1 of 1 (latest)

slate hamlet
#

Do I have to manually allocate an ArrayBuffer and encode as utf-8 with TextEncoder? Seems odd to me that you can't construct a CString from a regular js string and use that.
Either way, would be nice to have some examples of this in the docs :)

#

Oh, guess I forgot how TextEncoder works, it allocates the buffer for you. That makes it nicer :)

urban spear
#

yeah you convert it to format expected by function and pass it as pointer

#

the only important thing is to make sure buffer stays alive while ptr is in use

slate hamlet
#

Since there's a few footguns here (ensuring null-termination, keeping the buffer alive if C retains the pointer, etc.) I think it'd be worth having a section in the docs

#

I'll make an issue for that

urban spear
#

null termination is only needed if you use it as c string

#

which is not recommended if possible

slate hamlet
#

ofc, but some APIs require null termination

#

It's common enough to be worth mentioning

urban spear
#

yeah that’s the if possible part

crisp dragon
#

i agree the docs should clarify this

also kinda wish string handling could be better in general

urban spear
#

there is no better way to do it than make user hardcode behavior they need

#

it’s cheaper to add zero to rope in js than make whole ffi pad every string after turning rope into string

#

not to mention currently utf8 simd doesn’t return zero padded strings

#

one qol thing we could add is TextEncoder() that returns managed pointers