我有一个 WebGL unity 项目,它尝试在浏览器上执行 javascript 代码并返回一个值。
我的 Assets/Plugins/WebGL 文件夹中有以下 .jslib
文件:
var BrowserPlugin = {
GetEndpointURL: function()
{
var endpoint = window.itd.getEndpointUrl();
console.log("endpoint: " + endpoint);
return endpoint;
}
};
mergeInto(LibraryManager.library, BrowserPlugin);
在我的 Unity C# 代码中,我导入 dll 并调用我的 javascript 方法,如下所示:
[DllImport("__Internal")]
private static extern string GetEndpointURL();
string endpointURL = GetEndpointURL();
问题是,在我的 C# 代码中,endpointUrl
变量始终为 null。但是,在我的浏览器控制台中,我可以清楚地看到在返回之前正确的值已记录在浏览器 JavaScript 中。是什么导致该值恢复为空?
最佳答案
这是您的代码:
GetEndpointURL: function()
{
var endpoint = window.itd.getEndpointUrl();
console.log("endpoint: " + 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;
}
关于javascript - 从 Unity 中调用浏览器上的 javascript 字符串函数返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41654228/