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 即可。

  • 相关阅读:
    1.2基础--对象属性操作检测遍历
    C语言概览
    测试博客园字体
    c语言指针理解,指针的概念和演示指针的简单操作2
    c语言指针理解代码示例_函数返回指针变量_解除运算符获取指针的值
    c语言指针理解,指针的概念和演示指针的简单操作
    c语言指针概念解释_初步
    项目对文件分目录的感想
    visual studio快捷键
    java开源项目RuoYi若依管理系统
  • 原文地址:https://www.cnblogs.com/xsgame/p/3091071.html
Copyright © 2011-2022 走看看