All pastes #894615 Raw Edit

Untitled

public text v1 · immutable
·published 2008-02-07 02:46 UTC
rendered paste body
#include <stdio.h>
#include <string.h>
#include <jsapi.h>

static JSBool Test(JSContext *ctx, JSObject *obj, jsval id, jsval *vp)
{
    JSString *s = JS_NewStringCopyZ(ctx, "this is a test");
    *vp = STRING_TO_JSVAL(s);
    return JS_TRUE;
}

static JSBool Reset(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
    printf("in reset\n");
    return JS_TRUE;
}

static JSBool GetPropById(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
    printf("in GetPropById\n");
    return JS_TRUE;
}

JSPropertySpec properties[] = {
    { 0 }
};
JSFunctionSpec functions[] = {
    { "reset", Reset, 1, 0, 0 },
    { "getPropById", GetPropById, 1, 0, 0 },
    { 0 },
};

void
ReportError(JSContext *cx, const char *msg, JSErrorReport *report)
{
    printf("JS ERR [%s:%d]: %s\n", report->filename, report->lineno, msg);
}

int main(int argc, char **argv)
{
    JSRuntime *_runtime;
    JSContext *_context;
    JSObject *_global;
    JSClass _class;
    JSObject *_proto, *_parent;
    JSObject *_parentProto;

    _runtime = JS_NewRuntime(8*1024*1024);
    _context = JS_NewContext(_runtime, 8*1024);
    JS_SetErrorReporter(_context, ReportError);
    _global = JS_NewObject(_context, NULL, NULL, NULL);
    JS_InitStandardClasses(_context, _global);

    _parent = JS_GetGlobalObject(_context);

    memset(&_class, 0, sizeof(_class));
    _class.name = "foo";
    _class.flags = JSCLASS_HAS_PRIVATE;
    _class.addProperty = JS_PropertyStub;
    _class.delProperty = JS_PropertyStub;
    _class.getProperty = JS_PropertyStub;
    _class.setProperty = JS_PropertyStub;
    _class.enumerate = JS_EnumerateStub;
    _class.resolve = JS_ResolveStub;
    _class.convert = JS_ConvertStub;
    _class.finalize = JS_FinalizeStub;

    _proto = JS_InitClass(_context, _parent, NULL, &_class,
        NULL, 0, properties, functions,
        NULL, NULL);

    jsval ret;
    char *s = "var t = foo.reset(1);";
    JSBool r = JS_EvaluateScript(_context, _global, s, strlen(s),
        "reset", 0, &ret);

    s = "var t = foo.getPropById(1);";
    r = JS_EvaluateScript(_context, _global, s, strlen(s),
        "getPropById", 0, &ret);

    JS_DestroyContext(_context);
    JS_DestroyRuntime(_runtime);

    return 0;
}