Skip to content Skip to sidebar Skip to footer

Binding Native Objects With Javascriptcore C Api

I'm working on a project that is going to use JavascriptCore to run javascript in a native app. I'm able to bind a C native object with the JSClassDefinition class and set up the s

Solution 1:

I achieved to get the binding with these structures. I made the follow steps to do it.

1.- You should bind the Address structure as I did with Person.

2.- You have to create the bind method for the constructor for the Person structure and inside it initiate the Address object and set it as property like this:

// ConstructorJSObjectRefPersonCallAsConstructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, constJSValueRefarguments[], JSValueRef* exception){
Person *privObj = newPerson();

        if (argumentCount >= 2) {
            if (JSValueIsString(ctx, arguments[0]))
                privObj->name = JSStringToStdString(JSValueToStringCopy(ctx, arguments[0], nullptr));

            if (JSValueIsString(ctx, arguments[1]))
                privObj->lastName = JSStringToStdString(JSValueToStringCopy(ctx, arguments[1], nullptr));
        }

        // the third argument passed to the person constructor is the address streetif (argumentCount >= 3) {
            if (JSValueIsString(ctx, arguments[2]))
                privObj->address.street = JSStringToStdString(JSValueToStringCopy(ctx, arguments[2], nullptr));
        }

        // initiate a new Address objectJSObjectRef addressObj = AddressJSObjectMake(ctx, &privObj->address);
        JSObjectSetProperty(ctx, constructor, JSStringCreateWithUTF8CString("address"), addressObj, kJSPropertyAttributeNone, nullptr);

        JSObjectSetPrivate(constructor, static_cast<void*>(privObj));

        return constructor;
    }

Post a Comment for "Binding Native Objects With Javascriptcore C Api"