Calling javascript string function on browser from Unity returns null

♀尐吖头ヾ 提交于 2019-12-10 11:25:29

问题


I have a WebGL unity project which attempts to execute javascript code on the browser and return a value.

I have the following .jslib file in my Assets/Plugins/WebGL folder:

var BrowserPlugin = {
    GetEndpointURL: function()
    {
        var endpoint = window.itd.getEndpointUrl();

        console.log("endpoint: " + endpoint);

        return endpoint;
     }
};

mergeInto(LibraryManager.library, BrowserPlugin);

In my c# code in unity, I import the dll and call my javascript method like so:

[DllImport("__Internal")]
private static extern string GetEndpointURL();

string endpointURL = GetEndpointURL();

The problem is, in my c# code the endpointUrl variable is always null. However, in my browser console, I can clearly see the correct value is logged in the browser javascript before I return it. What is causing this value to come back to unity as null?


回答1:


This is your code:

GetEndpointURL: function()
{
    var endpoint = window.itd.getEndpointUrl();
    console.log("endpoint: " + endpoint);
    return endpoint;
}

You cannot return string (endpoint) directly. You have to create a buffer to hold that string and this process includes allocating memory with _malloc and copying old string to that new memory location with writeStringToMemory.

GetEndpointURL: function()
{
    var endpoint = window.itd.getEndpointUrl();
    console.log("endpoint: " + endpoint);

    var buffer = _malloc(lengthBytesUTF8(endpoint) + 1);
    writeStringToMemory(endpoint, buffer);
    return buffer;
}


来源:https://stackoverflow.com/questions/41654228/calling-javascript-string-function-on-browser-from-unity-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!