zoukankan      html  css  js  c++  java
  • NPAPI插件开发记录(四)NPAPI接受参数 字符串在Chrome下出现随机字符的问题。

    NPAPI接受参数字符串问题:

    在FireFox下正常 在Chrome下多了几个奇怪的字符。

    首先看看Stackoverflow上的这个问题,就是这篇文章要描述的,用一篇文章记录下来,是为了让遇到问题的人,用中文描述能够搜索到解决方案。

    JavaScript调用代码:

    plugin.method("a-b");

    NPAPI接受代码:

    bool ScriptablePluginObject::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) {
    
      char* outString = args[0].value.stringValue.UTF8Characters;
      char* npOutString = (char *)NPN_MemAlloc(strlen(outString) + 1);
      strcpy(npOutString, outString);
      STRINGZ_TO_NPVARIANT(npOutString, *result);
    
      return true;
    }

    结果:On Firefox, it returns "a-b", on Chrome, I will see "a-b*[-.." with some extra random symbols. 

    原因:You're missing the point; the string-handling functions you are using (strlen, strcpy) are designed to operate on NULL-terminated strings. You don't have a NULL-terminated string, you have a byte+length pair. You cannot use methods designed to operate on NULL-terminated strings on NPStrings. When it's working for you, it's by accident. You should be using UTF8Length instead of strlen(), and you should be using memcpy with a length and then NULL-terminating the result yourself. (When you forced shorter values in NPN_MemAlloc all you did is create a buffer overrun in your strcpy.)  不翻译了,关键是NPString.UTF8Length 。

    正确代码:

    bool ScriptablePluginObject::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) {
    
      char* outString = args[0].value.stringValue.UTF8Characters;
      int outLen = args[0].value.stringValue.UTF8Length;
      char* npOutString = (char *)NPN_MemAlloc(outLen + 1);
      memcpy(npOutString, outString, outLen);
      // Make this NULL terminated
      npOutString[outLen] = NULL;
      STRINGZ_TO_NPVARIANT(npOutString, *result);
    
      return true;
    }

    上述的例子,是返回给浏览器的字符串。如果只想接受用来处理,接收后的outString 截取长度为:args[0].value.stringValue.UTF8Length 即可。

  • 相关阅读:
    node的http与前端交互示例(入门)
    PC监听鼠标和键盘事件,定时无响应退出
    日常问题记录
    基于node.js的websocket 前后端交互小功能
    基于node.js的websocket上传小功能
    阿里云服务器(Linux)上打开新端口
    云服务器初尝试
    wx小程序知识点(八)
    wx小程序知识点(七)
    点绘,线绘,图绘
  • 原文地址:https://www.cnblogs.com/xsgame/p/3091071.html
Copyright © 2011-2022 走看看