Skip to content

Adding new extensions

bang edited this page Aug 18, 2015 · 3 revisions

##API

All extensions should extend JPExtension:

@interfaceJPExtension : 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 *)structDatadict:(NSDictionary *)dictstructDefine:(NSDictionary *)structDefine; + (NSDictionary *)getDictOfStruct:(void *)structDatastructDefine:(NSDictionary *)structDefine; @end

##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:

@interfaceJPMemory : JPExtension@end@implementationJPMemory + (void)main:(JSContext *)context { context[@"malloc"] = ^id(size_t size) { void *m = malloc(size); return [selfformatPointerOCToJS:m]; }; context[@"free"] = ^id(JSValue *jsVal) { void *m = [selfformatPointerJSToOC:jsVal]; free(m) }; } @end

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

require('JPEngine').addExtensions(['JPMemory'])varm=malloc(1024)free(m)
Clone this wiki locally
close