Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

QuickJS hello world, without qjs #135

Closed
anuragvohraec opened this issue Oct 13, 2022 · 2 comments
Closed

QuickJS hello world, without qjs #135

anuragvohraec opened this issue Oct 13, 2022 · 2 comments

Comments

@anuragvohraec
Copy link

Hi All,

I am new to quickjs.
I just wanted to use core JS-engine, without qjs or qjsc.

So I wrote up this hello world code in CPP (based on CMAKE, and linking the .o files of quickjs in the code).

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

# define MY_APP_VERSION 4

static void printFunction(const char* s){
    std::cout<<s<<std::endl;
}

JSValue js_print_func(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv){
    const char* s = JS_ToCString(ctx,argv[0]);
    printFunction(s);
    return JS_UNDEFINED;
}

int main(int argc, char** argv) {
    std::cout << "MyApp, version: " << MY_APP_VERSION <<std::endl;

    JSRuntime *rt=JS_NewRuntime();
    if(rt == NULL){
        std::cout << "Problem while getting JS runtime" << std::endl;
        return 1;
    }
    JSContext *ctx=JS_NewContext(rt);
    if (ctx == NULL) {
        JS_FreeRuntime(rt);
        std::cout << "Problem while getting JS context" << std::endl;
        return 1;
    }

    //Attaching a print1 prop to global object
    auto global_obj = JS_GetGlobalObject(ctx);
    JS_SetPropertyStr(ctx, global_obj, "print1",
                     JS_NewCFunction(ctx, js_print_func,"print1",1));


    //evaluating script
    const char* script = "print1('hello world');";
    auto val = JS_Eval(ctx,script, sizeof(script), "<evalScript>",JS_EVAL_TYPE_GLOBAL);

    if (JS_IsException(val)) {
        auto error = JS_GetException(ctx);
        std::cout<<JS_ToCString(ctx,error)<<std::endl;
    }

    std::cout << "MyApp stopped"<< std::endl;
}

I am not able to figure out what I am doing wrong , the eval always output :

MyApp, version: 4
SyntaxError: unexpected end of string
MyApp stopped

I have searched entire internet, which shows basic hello world example to get started.
Please can some one help me on this regards, how to correct this code.

@chqrlie
Copy link
Collaborator

chqrlie commented Oct 13, 2022 via email

@anuragvohraec
Copy link
Author

you pass sizeof(script), which is the size of a pointer, not the length of the string. You should instead pass strlen(script). Best Chqrlie.

I am feeling silly. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants