NPN_MemFree 后的 NPN_MemAlloc 将返回数据返回给 Google Chrome
我已经完成了我的 NPAPI 插件,它在 Google Chrome 中运行得很好,但有一个奇怪的问题。问题是我在插件中编写了一个方法,该方法将字符串返回到浏览器。为此,您必须在浏览器中分配内存并将结果字符串复制到其中。类似于:
bool
ScriptablePluginObject::Invoke(NPIdentifier name, const NPVariant *args,
uint32_t argCount, NPVariant *result)
{
if (name == sMethod_id) {
...
//free the memory if it is already allocated
if (m_pPtr) NPN_MemFree(m_pPtr);
//allocate the string in the browser memory
m_pPtr = (char*)NPN_MemAlloc(size+1);
SecureZeroMemory(m_pPtr, size+1);
memcpy(m_pATR, string, size);
//send result to browser
STRINGZ_TO_NPVARIANT(m_pPtr, *result);
return true;
}
...
}
请注意,“m_pPtr”是该类的数据成员,在构造时初始化为 NULL。当我从 Google Chrome 调用此方法两次时,就会出现问题。第一次效果很好。从第二次开始,依此类推,它会返回一个在浏览器中显示为“X”的垃圾值。我已经在 Firefox 中测试了相同的插件,无论我调用该方法多少次,它都能正常工作并返回正确的值。但是当我关闭加载插件的页面时,Firefox 崩溃了。
任何有关在这种奇怪情况下发生的事情的指示都会受到赞赏。我正在研究它,一旦获得任何有用的信息,我就会更新线程。
I've finished my NPAPI plug-in and it works great in Google Chrome but there's a strange problem. The problem is that I've coded a method in the plug-in that returns a string to the browser. In order to do so, you have to allocate a memory in the browser and copy the resulting string to it. Something like:
bool
ScriptablePluginObject::Invoke(NPIdentifier name, const NPVariant *args,
uint32_t argCount, NPVariant *result)
{
if (name == sMethod_id) {
...
//free the memory if it is already allocated
if (m_pPtr) NPN_MemFree(m_pPtr);
//allocate the string in the browser memory
m_pPtr = (char*)NPN_MemAlloc(size+1);
SecureZeroMemory(m_pPtr, size+1);
memcpy(m_pATR, string, size);
//send result to browser
STRINGZ_TO_NPVARIANT(m_pPtr, *result);
return true;
}
...
}
Note that 'm_pPtr' is a data member of the class and is initialized to NULL upon construction. The problem occurs when I call this method twice from Google Chrome. The first time it works great. From the second time and so on, it returns a garbage value displayed 'X' in the browser. I've tested the same plug-in in Firefox and it works fine and returns the correct value no matter how many times I call the method. But when I close the page which loaded the plug-in, then Firefox crashes.
Any pointers to what happens in this strange situation is appreciated. I'm working on it and will update the thread once I reach any useful information.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要删除以下行:
You are returned the string to the script and caller (在本例中为浏览器 JavaScript 引擎) 拥有它。
如果您释放它,这会导致未定义行为,因为内存可能仍在使用中或已经重新使用- 由浏览器使用或释放。
You need to remove the following line:
You are returning the string to the script and the caller (in this case the browsers JavaScript engine) owns it.
If you free it this leads to undefined behaviour as the memory could still be in use or already re-used or freed by the browser.