设为首页收藏本站|繁體中文

Project1

 找回密码
 注册会员
搜索
查看: 1473|回复: 0
打印 上一主题 下一主题

[原创发布] String#convert

[复制链接]

Lv4.逐梦者

梦石
0
星屑
6483
在线时间
119 小时
注册时间
2020-1-8
帖子
234
跳转到指定楼层
1
发表于 2022-1-23 20:38:51 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式

加入我们,或者,欢迎回来。

您需要 登录 才可以下载或查看,没有帐号?注册会员

x
本帖最后由 RPGzh500223 于 2022-1-23 20:40 编辑

参考资料:libconv

RUBY 代码复制
  1. class String
  2.   ICONV = "iconv.dll"
  3.  
  4.   Iconv_open = Win32API.new(ICONV, 'libiconv_open', 'PP', 'L')
  5.   Iconv_close = Win32API.new(ICONV, 'libiconv_close', 'L', 'L')
  6.   Iconv_do = Win32API.new(ICONV, 'libiconv', 'LPPPP', 'L')
  7.  
  8.   def convert(dst_charset, src_charset = 'UTF-8')
  9.     dst_str = "\0" * (self.size << 1)
  10.     iconv_t = Iconv_open.call(dst_charset, src_charset)
  11.     return if iconv_t == -1
  12.     inbuf = [self].pack('p')
  13.     inbytesleft = [self.size].pack('L')
  14.     outbuf = [dst_str].pack('p')
  15.     outbytesleft = [dst_str.size].pack('L')
  16.     Iconv_do.call(iconv_t, inbuf, inbytesleft, outbuf, outbytesleft)
  17.     Iconv_close.call(iconv_t)
  18.     return dst_str[0, dst_str.size - outbytesleft.unpack('L')[0]]
  19.   end
  20.  
  21.   CallWndProc = Win32API.new('user32', 'CallWindowProc', 'PLLLL', 'L')
  22.   GetProcAddress = Win32API.new('kernel32', 'GetProcAddress', 'LP', 'L')
  23.   LoadLibrary = Win32API.new('kernel32', 'LoadLibrary', 'P', 'L')  
  24.   HICONV = LoadLibrary.call(ICONV)  
  25.   ProcAddr = [GetProcAddress.call(HICONV, 'libiconv_open'),
  26.               GetProcAddress.call(HICONV, 'libiconv'),
  27.               GetProcAddress.call(HICONV, 'libiconv_close')].pack('L3')
  28.  
  29.   CodeIconv = [85,139,236,139,69,8,139,28,69,16,0,0,0,139,83,4,255,114,12,
  30.     139,19,255,114,12,139,69,20,139,28,69,12,0,0,0,62,137,93,20,255,19,131,
  31.     196,8,131,248,255,116,110,62,137,69,8,139,125,12,209,231,131,199,8,255,
  32.     55,255,119,4,139,117,16,209,230,131,198,8,255,54,255,118,4,87,131,199,
  33.     4,87,86,131,198,4,86,62,255,117,8,139,93,20,255,83,4,131,196,20,139,93,
  34.     16,143,4,93,12,0,0,0,143,4,93,8,0,0,0,139,93,12,143,4,93,12,0,0,0,88,
  35.     43,4,93,8,0,0,0,137,4,93,8,0,0,0,80,62,255,117,8,139,93,20,255,83,8,
  36.     131,196,4,88,201,194,16,0].pack('C*')
  37.   def convert2(dst_charset, src_charset = 'UTF-8')
  38.     dst_str = "\0" * (self.size << 1)
  39.     bytes = CallWndProc.call(CodeIconv, [dst_charset, src_charset].object_id,
  40.       dst_str.object_id, self.object_id, ProcAddr.object_id)
  41.     dst_str
  42.   end
  43. end



String#convert2和String#convert都是调用DLL,前者效率稍高,至于DLL网上搜索下载即可
效率没有win32api快,但是支持的编码更多,具体可以看上面的链接

500字符的中文 UTF-8 转 GBK 测试 (具体次数好像和电脑性能相关,我的电脑 RMXP  Time无执行代码测试 21.9-22.2W次/秒)


效率测试.png (3.45 KB, 下载次数: 19)

效率测试.png
您需要登录后才可以回帖 登录 | 注册会员

本版积分规则

拿上你的纸笔,建造一个属于你的梦想世界,加入吧。
 注册会员
找回密码

站长信箱:[email protected]|手机版|小黑屋|无图版|Project1游戏制作

GMT+8, 2024-11-23 00:23

Powered by Discuz! X3.1

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表