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

posted on 2013-05-21 17:01  潜心止水  阅读(939)  评论(0编辑  收藏  举报