WebAssembly working with strings

816 views Asked by At

Why does web assembly method cannot take or return arguments such as a simple UTF-8 string or an array of characters, i.e. something like:

char* testMethod(int a)
{
    return "bla bla";
}

I have read that instances of complex classes (objects) should be placed in "WebAssembly memory". Since webassembly is a stack machine this should be some kind of a heap.

However, I do not quite understand the following thing related to objects like "String". If we say that String is an array of chars, then we can say: well, char is a number, and thus we have a string which represents a series of those number (chars), then I get a byte buffer with some particular length. String is object on which we do not know it's length in advance and thus we cannot allocate it, therefore there is that magical place called "the WebAssembly memory"/heap where that object is being stored.

So far all good but if I understood correctly we can only pass pointers in the methods of the web assembly in order to access those complex object. Thus the question: how does web assembly know when it should stop reading?

For example, I am thinking directions TLV i.e. type length values related to a string object. If we only have the pointer which is directing us to the beginning of where we have to start reading then how do we know when should we stop reading if we do not have the length or is there some special character that is saying now you should stop reading or am I missing something?

I would really appreciate if someone elaborates on how webassembly memory works and how and when webassembly memory is being allocated? Does this correspond to malloc and free?

Rephrasing the question;

Why does hello world mentioned here http://webassembly.org/getting-started/developers-guide/

works but I can not have another method with the same signature return string. The hello world is in that example a string as well.

0

There are 0 answers