NPAPI plugin_invoke函数返回字符串值垃圾字符



npapi code:

bool plugin_invoke(NPObject *obj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result) {
NPUTF8 *name = browser->utf8fromidentifier(methodName);
if(strcmp(name, plugin_method_name_getAddress) == 0){
    NPString password;
    if(argCount > 0) {
        password = NPVARIANT_TO_STRING(args[0]);
    }
    const char * StringVariable = password.UTF8Characters;
    char* npOutString = (char *)malloc(strlen(StringVariable+1));
    if (!npOutString)
        return false;
    strcpy(npOutString, StringVariable);
    STRINGZ_TO_NPVARIANT(npOutString, *result);
    browser->memfree(name);
    return true;
}
return false;

}

网页代码:

function run() {
    var plugin = document.getElementById("pluginId");
    var passwordBeforEncryption =  document.getElementById("passwordFeild");
    if(plugin){
        var value = plugin.getAddress("hello, just test it");
            alert(value);
    }else{
        alert("plugin is null");
    }

}

正确的结果应该是:"你好,只是测试它

",但有时返回"你好,只是测试它"。只是有时不是所有时间!

请帮忙。

错误不在您的 html 中,您应该看到 NPString 结构。

typedef struct _NPString {
    const NPUTF8 *UTF8Characters;
    uint32_t UTF8Length;
} NPString;

成员 UTF8Length 表示字符串的长度,因此您应该执行以下操作:

const char * StringVariable = password.UTF8Characters;
char* npOutString  = (char*)browser->memalloc(password.UTF8Length+1);
if (!npOutString) {
    return false;
}
memcpy(npOutString  , password.UTF8Characters, password.UTF8Length);
npOutString[password.UTF8Length] = 0;

看起来您分配了不正确的内存:

char* npOutString = (char *)malloc(strlen(StringVariable+1));

应该是:

char* npOutString = (char *)malloc(strlen(StringVariable)+1);

以更正长度。

但是,为了使浏览器能够释放内存,您应该使用:

char* npOutString = (char *)NPN_MemAlloc(strlen(StringVariable)+1);

好的,喜欢这个答案!在 html 代码中:

var value = plugin.getAddress("hello, just test it");

应该是这样的:

var value = plugin.getAddress("hello, just test it");

在字符串末尾需要"\0"

相关内容

  • 没有找到相关文章

最新更新