Adding new extensions

bang edited this page Aug 18, 2015 · 3 revisions


All extensions should extend JPExtension:

@interface JPExtension : NSObject
+ (void)main:(JSContext *)context;

+ (void *)formatPointerJSToOC:(JSValue *)val;
+ (id)formatPointerOCToJS:(void *)pointer;
+ (id)formatJSToOC:(JSValue *)val;
+ (id)formatOCToJS:(id)obj;

+ (int)sizeOfStructTypes:(NSString *)structTypes;
+ (void)getStructDataWidthDict:(void *)structData dict:(NSDictionary *)dict structDefine:(NSDictionary *)structDefine;
+ (NSDictionary *)getDictOfStruct:(void *)structData structDefine:(NSDictionary *)structDefine;

Add C function support

The +main: method in JPExtension will be executed when the extension added to JPEngine, so we can add JS methods in +main:.

The 4 formatXXX methods are used for translate types through OC and JS, use -formatPointerJSToOC: / -formatJSToOC: to convert params from JS to OC, use -formatPointerOCToJS: / -formatOCToJS: to convert return value from OC to JS. Example:

@interface JPMemory : JPExtension

@implementation JPMemory
+ (void)main:(JSContext *)context
    context[@"malloc"] = ^id(size_t size) {
        void *m = malloc(size);
        return [self formatPointerOCToJS:m];

    context[@"free"] = ^id(JSValue *jsVal) {
        void *m = [self formatPointerJSToOC:jsVal];

Now we can use malloc() and free() in JS:

var m = malloc(1024)