- Home /
jslib is passing string as number
When trying to use the jslib as documented here https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html my function with all string parameters is being passed as number values. The console.log in the web browser shows that url and url2 are numbers, when they should be strings.
Code:
//jslib:
var websocketJSLib = {
wss : null,
StartMMJS : function(url, url2) {
console.log("js connecting to " + url2);
console.log(url2);
console.log(typeof(url2));
console.log("2 js connecting to " + url2.toString() + " --" + String(url2));
console.log(url2);
console.log(typeof(url2));
wss = new WebSocket(url);
},
}
mergeInto(LibraryManager.library, websocketJSLib);
//cs code:
public class test : MonoBehaviour {
// Use this for initialization
void Start () {
Debug.LogWarning("4 cs booting");
StartMM("ws://mm.myserver.com/MM");
}
[DllImport("__Internal")]
private static extern void StartMMJS(string url, string url2);
public void StartMM(string server)
{
Debug.LogWarning("4 cs connecting to " + server);
StartMMJS("ws://mm.myserver.com/MM", server);
}
}
Answer by Bunny83 · Jul 23, 2018 at 09:25 AM
Just came along this question. You said you implemented your jslib like documented, but you actually didn't. Your "managed" C# code actually runs in a virtual machine that is implemented in javascript. However it has it's own memory management. In the documentation there's an example of passing a string argument to a js function:
HelloString: function (str) {
window.alert(Pointer_stringify(str));
},
That means a managed string (which is a managed object in the managed heap) has to be converted to a js string using Pointer_stringify(str)
Note that returning a string to C# / Mono is actually a bit more complex as you have to allocate the memory in the managed heap first. Though there's also an example in the docs.
This reply saved me ;) . Now Pointer_stringify(str);
is obsolete, UTF8ToString(str);
is the replacement.