electron通过node-ffi调用dll传参数格式问题,utf8转utf16

dll那边接入参数,需要utf16le (小端)无BOM格式,而nodejs这里字符串默认为utf8

网上很多通过iconv-lite转码,实际使用过程中并不理想。

通过不断的摸索,写了如下的转码函数

//处理编码
function encode(str, sort = "le") {
  let resultArr = [];
  for (let i = 0; i < str.length; i++) {
    let utf16le = str.charCodeAt(i).toString(16);
    let highByte = utf16le.substr(0, 2);
    let lowByte = utf16le.substr(2, 4);
    if (!lowByte) {//如果没有低位
      lowByte = highByte;
      highByte = "00";
    }
    let high = "0x" + highByte;
    let low = "0x" + lowByte;

    if (sort == "be") {//大端
      resultArr.push(high)
      resultArr.push(low)
    } else if (sort == "le") {//小端
      resultArr.push(low)
      resultArr.push(high)
    }
  }
  resultArr.push("\0");
  return Buffer.from(resultArr);
}

 

你可能感兴趣的:(node,electron)