从 Unity 在浏览器上调用 javascript 字符串函数 returns null

Calling javascript string function on browser from Unity returns null

我有一个 WebGL 统一项目,它试图在浏览器上执行 javascript 代码和 return 一个值。

我的 Assets/Plugins/WebGL 文件夹中有以下 .jslib 文件:

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

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

        return endpoint;
     }
};

mergeInto(LibraryManager.library, BrowserPlugin);

在我统一的 C# 代码中,我导入了 dll 并像这样调用我的 javascript 方法:

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

string endpointURL = GetEndpointURL();

问题是,在我的 C# 代码中,endpointUrl 变量始终为空。但是,在我的浏览器控制台中,我可以清楚地看到在 return 之前浏览器中记录了正确的值 javascript。是什么导致此值恢复为 null?

这是您的代码:

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

不能 return 字符串(endpoint) 直接。您必须创建一个缓冲区来保存该字符串,此过程包括使用 _malloc 分配内存并使用 writeStringToMemory.

将旧字符串复制到新的内存位置
GetEndpointURL: function()
{
    var endpoint = window.itd.getEndpointUrl();
    console.log("endpoint: " + endpoint);

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