Return string from UnityWebGL jslib

2019-07-23 05:25发布

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条回答
闹够了就滚
2楼-- · 2019-07-23 06:15

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;
}
查看更多
登录 后发表回答