forked from bang590/JSPatch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JPMemory.m
95 lines (77 loc) · 2.88 KB
/
JPMemory.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//
// JPMemory.m
// JSPatchDemo
//
// Created by Albert438 on 15/7/6.
// Copyright (c) 2015年 bang. All rights reserved.
//
#import "JPMemory.h"
@implementation JPMemory
+ (void)main:(JSContext *)context
{
context[@"memset"] = ^void(JSValue *jsVal, int ch,size_t n) {
memset([self formatPointerJSToOC:jsVal], ch, n);
};
context[@"memmove"] = ^id(JSValue *des, JSValue *src, size_t n) {
void *ret = memmove([self formatPointerJSToOC:des], [self formatPointerJSToOC:src], n);
return [self formatPointerOCToJS:ret];
};
context[@"memcpy"] = ^id(JSValue *des, JSValue *src, size_t n) {
void *ret = memcpy([self formatPointerJSToOC:des], [self formatPointerJSToOC:src], n);
return [self formatPointerOCToJS:ret];
};
context[@"malloc"] = ^id(size_t size) {
void *m = malloc(size);
return [self formatPointerOCToJS:m];
};
context[@"free"] = ^void(JSValue *jsVal) {
void *m = [self formatPointerJSToOC:jsVal];
free(m);
};
context[@"pval"] = ^id(JSValue *jsVal) {
void *m = [self formatPointerJSToOC:jsVal];
id obj = *((__unsafe_unretained id *)m);
return [self formatOCToJS:obj];
};
context[@"getPointer"] = ^id(JSValue *jsVal) {
void **p = malloc(sizeof(void *));
void *pointer = [self formatPointerJSToOC:jsVal];
if (pointer != NULL) {
*p = pointer;
} else {
id obj = [self formatJSToOC:jsVal];
*p = (__bridge void*)obj;
}
return [self formatPointerOCToJS:p];
};
context[@"pvalBool"] = ^id(JSValue *jsVal) {
void *m = [self formatPointerJSToOC:jsVal];
BOOL b = *((BOOL *)m);
return [self formatOCToJS:[NSNumber numberWithBool:b]];
};
__weak JSContext *weakCtx = context;
context[@"sizeof"] = ^size_t(JSValue *jsVal) {
NSString *typeName = [jsVal toString];
if ([typeName isEqualToString:@"id"]) return sizeof(id);
if ([typeName isEqualToString:@"CGRect"]) return sizeof(CGRect);
if ([typeName isEqualToString:@"CGPoint"]) return sizeof(CGPoint);
if ([typeName isEqualToString:@"CGSize"]) return sizeof(CGSize);
if ([typeName isEqualToString:@"NSRange"]) return sizeof(NSRange);
@synchronized (weakCtx) {
NSDictionary *structDefine = [JPExtension registeredStruct][typeName];
if (structDefine) {
return [self sizeOfStructTypes:structDefine[@"types"]];
}
}
return 0;
};
context[@"__bridge_id"] = ^id(JSValue *jsVal) {
void *p = [self formatPointerJSToOC:jsVal];
id obj = (__bridge id)p;
return [self formatOCToJS:obj];
};
context[@"CFRelease"] = ^void(JSValue *jsVal) {
CFRelease([self formatPointerJSToOC:jsVal]);
};
}
@end