Return string from UnityWebGL jslib

家住魔仙堡 提交于 2019-12-11 01:59:52

问题


I want use jslib to get url parameter

code like this

jslib

  GetUrl: function(){
  var s ="";
  var strUrl = window.location.search;
  var getSearch = strUrl.split("?");
  var getPara = getSearch[1].split("&");
  var v1 = getPara[0].split("=");
        alert(v1[1]);
   return v1[1];
  },
});

c#

[DllImport("__Internal")]
public static extern string GetUrl();


void Start () {
    TextShow.text = GetUrl();
}

When run alert from jslib , I see right string show in alert but UGUI Text shows nothing.

Why did this happen?


回答1:


To return string from Javascript to Unity, you must use _malloc to allocate memory then writeStringToMemory to copy the string data from your v1[1] variable into the newly allocated memory then return that.

GetUrl: function()
{
  var s ="";
  var strUrl = window.location.search;
  var getSearch = strUrl.split("?");
  var getPara = getSearch[1].split("&");
  var v1 = getPara[0].split("=");
  alert(v1[1]);


   //Allocate memory space
   var buffer = _malloc(lengthBytesUTF8(v1[1]) + 1);
   //Copy old data to the new one then return it
   writeStringToMemory(v1[1], buffer);
   return buffer;
}

The writeStringToMemory function seems to be deprecated now but you can still do the-same thing with stringToUTF8 and proving the size of the string in its third argument.

GetUrl: function()
{
  var s ="";
  var strUrl = window.location.search;
  var getSearch = strUrl.split("?");
  var getPara = getSearch[1].split("&");
  var v1 = getPara[0].split("=");
  alert(v1[1]);


   //Get size of the string
   var bufferSize = lengthBytesUTF8(v1[1]) + 1;
   //Allocate memory space
   var buffer = _malloc(bufferSize);
   //Copy old data to the new one then return it
   stringToUTF8(v1[1], buffer, bufferSize);
   return buffer;
}


来源:https://stackoverflow.com/questions/52111679/return-string-from-unitywebgl-jslib

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