c++ 在Quickjs中,什么是在结构中捕获字符串的正确方法

6ju8rftf  于 2023-01-18  发布在  其他
关注(0)|答案(1)|浏览(226)

bounty将于明天过期。此问题的答案可获得+50的声誉奖励。Anurag Vohra正在寻找来自声誉良好来源的答案:如何运行这段代码没有任何内存问题。

我有这样的结构:

struct EventState{
std::string type;
};

我在类的constructor中设置了这个结构

eventState->type=JS_ToCString(ctx, argv[0]);

这条线似乎会导致记忆丢失的问题,因为我的valgrind抱怨6 bytes in 1 blocks are definitely lost in loss record 1 of 2,在这条线上。
在quickjs中,如何在没有内存问题的情况下捕获这个字符串用于内部用途呢?
根据要求,以下是可报告的最小示例:

#include <quickjs/quickjs.h>
#include <iostream>

JSClassID newClassId=0;

struct EventState{
    std::string type;
};

static JSValue js_print(JSContext *ctx, JSValueConst this_val,
                        int argc, JSValueConst *argv)
{
    auto str = JS_ToCString(ctx, argv[0]);
    std::cout << "msg: "<<str << std::endl;
    JS_FreeCString(ctx, str);
    return JS_UNDEFINED;
}

static JSValue Event_constructor(JSContext *ctx, JSValueConst new_target,int argc, JSValueConst *argv){
    JSValue prototype;
    JSValue result=JS_UNDEFINED;
    auto id = newClassId;
    
    prototype = JS_GetPropertyStr(ctx,new_target,"prototype");

    if(JS_IsException(result)){
        return JS_EXCEPTION;
    }

    if(argc==0 || !JS_IsString(argv[0])){
        return JS_ThrowTypeError(ctx, "%s","Invalid event type");
    }
    
    result= JS_NewObjectProtoClass(ctx,prototype,id);
    JS_FreeValue(ctx, prototype);
    
    //set opaque if internal state needs to be maintained
    auto eventState = (EventState*)js_mallocz(ctx, sizeof(EventState));
    auto t = JS_ToCString(ctx, argv[0]);
    eventState->type=t;
    JS_FreeCString(ctx, t);
    JS_SetOpaque(result, eventState);

    return result;
}

static JSValue set_readonly(JSContext *ctx, JSValueConst this_val, JSValue val,int magic){
    return JS_UNDEFINED;
}
static JSValue get_type_Event(JSContext *ctx, JSValueConst this_val,int magic){
    auto eventState = (EventState*)JS_GetOpaque(this_val, newClassId);
    return JS_NewString(ctx, &eventState->type[0]);
}

JSCFunctionListEntry Event_instanceMethods[1]={
    JS_CGETSET_MAGIC_DEF("type", get_type_Event, set_readonly,0),
};

void registerEventClass(JSContext *ctx){
    JSClassID id=0;
    newClassId = JS_NewClassID(&id);
    auto rt = JS_GetRuntime(ctx);
    char* className ="Event";

    JSClassDef  classDef;
    classDef.class_name=className;
    classDef.finalizer=[](JSRuntime* rt, JSValue val){
        auto s  = (EventState*)JS_GetOpaque(val, newClassId);
        if(s!=NULL){
            js_free_rt(rt, s);
        }
    };
    classDef.gc_mark=NULL;
    classDef.exotic=NULL;
    classDef.call=NULL;

    JS_NewClass(rt,newClassId,&classDef);
    
    JSValue prototype =JS_NewObject(ctx);
    //adding instance methods
    JS_SetPropertyFunctionList(ctx,prototype,Event_instanceMethods,1);

    auto new_class = JS_NewCFunction2(ctx,Event_constructor,className,1,JS_CFUNC_constructor,0);
    auto global_obj=JS_GetGlobalObject(ctx);
    JS_DefinePropertyValueStr(ctx, global_obj, className,
                        JS_DupValue(ctx, new_class),
                        JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
    JS_SetConstructor(ctx, new_class, prototype);
    JS_SetClassProto(ctx,newClassId,prototype);

    JS_FreeValue(ctx, new_class);
    JS_FreeValue(ctx,global_obj);

}

int main(){
        JSRuntime *rt;
        JSContext *ctx;
        JSValue evalVal;

        rt = JS_NewRuntime();
        ctx = JS_NewContext(rt);
        
        registerEventClass(ctx);

        auto global_object = JS_GetGlobalObject(ctx);
        auto printF = JS_NewCFunction(ctx, js_print, "print", 1);
        JS_SetPropertyStr(ctx, global_object, "print", printF);
        
        evalVal = JS_Eval(ctx, "let e = new Event('test1');\nprint(e.type);", 42, "<input>", 0);
        
        JS_FreeValue(ctx,global_object);
        JS_FreeValue(ctx, evalVal);
        
        JS_FreeContext(ctx);
        JS_FreeRuntime(rt);
        return 0;
}
czq61nw1

czq61nw11#

好吧,你不能使用std::String来存储Quickjs生成的字符串,这似乎会产生这样的问题。由于std::string是由C++管理的,并且创建字符串的内存在QuickJS运行时的堆中。
所以你的结构应该是这样的:

struct EventState{
    char* type;
};

然后你需要像这样复制类型:

auto t = JS_ToCString(ctx, argv[0]);
eventState->type = strdup(t); //we will still need to free this
JS_FreeCString(ctx, t);

稍后在终结器中使用free释放此eventState->type内存

classDef.finalizer=[](JSRuntime* rt, JSValue val){
auto s  = (EventState*)JS_GetOpaque(val, newClassId);
if(s!=NULL){
    free(s->type);
    js_free_rt(rt, s);
 }
};

下面是完整的最小运行代码示例,没有内存问题:

#include <cstdlib>
#include <quickjs/quickjs.h>
#include <iostream>
#include <cstring>

JSClassID newClassId=0;

struct EventState{
    char* type;
};

static JSValue js_print(JSContext *ctx, JSValueConst this_val,
                        int argc, JSValueConst *argv)
{
    auto str = JS_ToCString(ctx, argv[0]);
    std::cout << "msg: "<<str << std::endl;
    JS_FreeCString(ctx, str);
    return JS_UNDEFINED;
}

static JSValue Event_constructor(JSContext *ctx, JSValueConst new_target,int argc, JSValueConst *argv){
    JSValue prototype;
    JSValue result=JS_UNDEFINED;
    auto id = newClassId;
    
    prototype = JS_GetPropertyStr(ctx,new_target,"prototype");

    if(JS_IsException(result)){
        return JS_EXCEPTION;
    }

    if(argc==0 || !JS_IsString(argv[0])){
        return JS_ThrowTypeError(ctx, "%s","Invalid event type");
    }
    
    result= JS_NewObjectProtoClass(ctx,prototype,id);
    JS_FreeValue(ctx, prototype);
    
    //set opaque if internal state needs to be maintained
    auto eventState = (EventState*)js_mallocz(ctx, sizeof(EventState));
    auto t = JS_ToCString(ctx, argv[0]);
    eventState->type = strdup(t);
    JS_FreeCString(ctx, t);
    JS_SetOpaque(result, eventState);

    return result;
}

static JSValue set_readonly(JSContext *ctx, JSValueConst this_val, JSValue val,int magic){
    return JS_UNDEFINED;
}
static JSValue get_type_Event(JSContext *ctx, JSValueConst this_val,int magic){
    auto eventState = (EventState*)JS_GetOpaque(this_val, newClassId);
    return JS_NewString(ctx, &eventState->type[0]);
}

JSCFunctionListEntry Event_instanceMethods[1]={
    JS_CGETSET_MAGIC_DEF("type", get_type_Event, set_readonly,0),
};

void registerEventClass(JSContext *ctx){
    JSClassID id=0;
    newClassId = JS_NewClassID(&id);
    auto rt = JS_GetRuntime(ctx);
    char* className ="Event";

    JSClassDef  classDef;
    classDef.class_name=className;
    classDef.finalizer=[](JSRuntime* rt, JSValue val){
        auto s  = (EventState*)JS_GetOpaque(val, newClassId);
        if(s!=NULL){
            free(s->type);
            js_free_rt(rt, s);
        }
    };
    classDef.gc_mark=NULL;
    classDef.exotic=NULL;
    classDef.call=NULL;

    JS_NewClass(rt,newClassId,&classDef);
    
    JSValue prototype =JS_NewObject(ctx);
    //adding instance methods
    JS_SetPropertyFunctionList(ctx,prototype,Event_instanceMethods,1);

    auto new_class = JS_NewCFunction2(ctx,Event_constructor,className,1,JS_CFUNC_constructor,0);
    auto global_obj=JS_GetGlobalObject(ctx);
    JS_DefinePropertyValueStr(ctx, global_obj, className,
                        JS_DupValue(ctx, new_class),
                        JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
    JS_SetConstructor(ctx, new_class, prototype);
    JS_SetClassProto(ctx,newClassId,prototype);

    JS_FreeValue(ctx, new_class);
    JS_FreeValue(ctx,global_obj);

}

int main(){
        JSRuntime *rt;
        JSContext *ctx;
        JSValue evalVal;

        rt = JS_NewRuntime();
        ctx = JS_NewContext(rt);
        
        registerEventClass(ctx);

        auto global_object = JS_GetGlobalObject(ctx);
        auto printF = JS_NewCFunction(ctx, js_print, "print", 1);
        JS_SetPropertyStr(ctx, global_object, "print", printF);
        
        evalVal = JS_Eval(ctx, "let e = new Event('test1');\nprint(e.type);", 42, "<input>", 0);
        
        JS_FreeValue(ctx,global_object);
        JS_FreeValue(ctx, evalVal);
        
        JS_FreeContext(ctx);
        JS_FreeRuntime(rt);
        return 0;
}

相关问题