forked from timob/jnigi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jnigi.go
2172 lines (1919 loc) · 57 KB
/
jnigi.go
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 Tim O'Brien. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
JNIGI (Java Native Interface Go Interface)
A package to access Java from Go code.
All constructor and method call functions convert parameter arguments and return values.
Arguments are converted from Go to Java if:
- The type is Go built in type and there is an equivalent Java primitive type.
- The type is a slice of such a Go built in type.
- The type implements the ToJavaConverter interface
Return values are converted from Java to Go if:
- The type is a Java primitive type.
- The type is a Java array of a primitive type.
- The type implements the ToGoConverter interface
Go Builtin to/from Java Primitive:
bool Boolean
byte Byte
int16 Short
uint16 Char
int Int (also int32 -> Int)
int64 Long
float32 Float
float64 Double
*/
package jnigi
import (
"errors"
"fmt"
"strings"
"unsafe"
)
// copy arguments in to C memory before passing to jni functions
var copyToC bool = false
func toBool(b jboolean) bool {
return b == 1
}
func fromBool(b bool) jboolean {
if b {
return 1
} else {
return 0
}
}
// ObjectRef holds a reference to a Java Object
type ObjectRef struct {
jobject jobject
className string
isArray bool
}
// NewObjectRef returns new *ObjectRef with Nil JNI object reference and class name set to className.
func NewObjectRef(className string) *ObjectRef {
return &ObjectRef{0, className, false}
}
// NewObjectArrayRef returns new *ObjectRef with Nil JNI object array reference and class name set to className.
func NewObjectArrayRef(className string) *ObjectRef {
return &ObjectRef{0, className, true}
}
// WrapJObject wraps a JNI object value in an ObjectRef
func WrapJObject(jobj uintptr, className string, isArray bool) *ObjectRef {
return &ObjectRef{jobject(jobj), className, isArray}
}
// GetClassName returns class name of object reference.
func (o *ObjectRef) GetClassName() string {
return o.className
}
// IsArray returns true if reference is to object array.
func (o *ObjectRef) IsArray() bool {
return o.isArray
}
// Cast return a new *ObjectRef containing the receiver jobject and with class name set to className.
func (o *ObjectRef) Cast(className string) *ObjectRef {
return &ObjectRef{o.jobject, className, o.isArray}
}
// IsNil is true if ObjectRef has a Nil Java value
func (o *ObjectRef) IsNil() bool {
return o.jobject == 0
}
// IsInstanceOf returns true if o is an instance of className
func (o *ObjectRef) IsInstanceOf(env *Env, className string) (bool, error) {
class, err := env.callFindClass(className)
if err != nil {
return false, err
}
return toBool(isInstanceOf(env.jniEnv, o.jobject, class)), nil
}
func (o *ObjectRef) jobj() jobject {
return o.jobject
}
// JObject gets JNI object value of o
func (o *ObjectRef) JObject() jobject {
return o.jobj()
}
type jobj interface {
jobj() jobject
}
// ExceptionHandler is used to convert a thrown exception (java.lang.Throwable) to a Go error.
type ExceptionHandler interface {
CatchException(env *Env, exception *ObjectRef) error
}
// ExceptionHandlerFunc is an adapter to allow use of ordinary functions as an
// ExceptionHandler. If f is a function with the appropriate signature, ExceptionHandlerFunc(f)
// is an ExceptionHandler object that calls f.
type ExceptionHandlerFunc func(env *Env, exception *ObjectRef) error
// CatchException calls f to implement ExceptionHandler.
func (f ExceptionHandlerFunc) CatchException(env *Env, exception *ObjectRef) error {
return f(env, exception)
}
// Env holds a JNIEnv value. Methods in this package often require an *Env pointer to specify
// the JNI Env to run in, so it might be good to store the Env as a package variable.
type Env struct {
jniEnv unsafe.Pointer
preCalcSig string
classCache map[string]jclass
addtlClassLoader unsafe.Pointer
ExceptionHandler ExceptionHandler
}
// WrapEnv wraps an JNI Env value in an Env
func WrapEnv(envPtr unsafe.Pointer) *Env {
return &Env{jniEnv: envPtr, classCache: make(map[string]jclass)}
}
// JVM holds a JavaVM value, you only need one of these in your app.
type JVM struct {
javaVM unsafe.Pointer
addtlClassLoader unsafe.Pointer
}
// JVMInitArgs holds a JavaVMInitArgs value
type JVMInitArgs struct {
javaVMInitArgs unsafe.Pointer
}
// CreateJVM calls JNI CreateJavaVM and returns references to the JVM and the initial environment.
// Use NewJVMInitArgs to create jvmInitArgs.
//
// Must call runtime.LockOSThread() first.
func CreateJVM(jvmInitArgs *JVMInitArgs) (*JVM, *Env, error) {
p := malloc(unsafe.Sizeof((unsafe.Pointer)(nil)))
p2 := malloc(unsafe.Sizeof((unsafe.Pointer)(nil)))
if jni_CreateJavaVM(p2, p, jvmInitArgs.javaVMInitArgs) < 0 {
return nil, nil, errors.New("Couldn't instantiate JVM")
}
jvm := &JVM{javaVM: *(*unsafe.Pointer)(p2)}
env := &Env{jniEnv: *(*unsafe.Pointer)(p), classCache: make(map[string]jclass)}
free(p)
free(p2)
return jvm, env, nil
}
// UseJVM initialized jnigi with an existing JVM.
//
// This is important for Android, where the existing JVM must be used when running inside an
// Android app--i.e. Go code built as a shared library.
//
// An existing JVM may be obtained through a JNI call made by the JVM after System.loadLibrary:
//
// JNIEXPORT void JNICALL Java_foo_bar_Baz_00024_funcName(JNIEnv *env, jobject thiz) {
// // Pass env, thiz and the result of (*env)->GetJavaVM() into Go, then UseJVM()
// }
//
// If 'thiz' is specified, its class loader will be used to find non-system classes.
// This should pick up custom classes, as well as libraries from dependencies { } in build.gradle.
//
// Parameters can also be derived from the JNI_OnLoad() call made during System.loadLibrary().
// In this case, 'thiz' should be a custom class in order to retrieve a useful class loader.
func UseJVM(pvm unsafe.Pointer, penv unsafe.Pointer, thiz unsafe.Pointer) (*JVM, *Env) {
var classLoader unsafe.Pointer
if thiz != nil {
classLoader = getClassLoader(penv, thiz)
}
jvm := &JVM{javaVM: pvm, addtlClassLoader: classLoader}
env := &Env{jniEnv: penv, classCache: make(map[string]jclass), addtlClassLoader: classLoader}
return jvm, env
}
// AttachCurrentThread calls JNI AttachCurrentThread.
// Must call runtime.LockOSThread() first.
func (j *JVM) AttachCurrentThread() *Env {
p := malloc(unsafe.Sizeof((unsafe.Pointer)(nil)))
// p := (**C.JNIEnv)(malloc(unsafe.Sizeof((*C.JNIEnv)(nil))))
if attachCurrentThread(j.javaVM, p, nil) < 0 {
panic("AttachCurrentThread failed")
}
return &Env{
jniEnv: *(*unsafe.Pointer)(p),
classCache: make(map[string]jclass),
addtlClassLoader: j.addtlClassLoader,
}
}
// DetachCurrentThread calls JNI DetachCurrentThread, pass Env returned from AttachCurrentThread for current thread.
func (j *JVM) DetachCurrentThread(env *Env) error {
//free cache
for _, v := range env.classCache {
deleteGlobalRef(env.jniEnv, jobject(v))
}
if detachCurrentThread(j.javaVM) < 0 {
return errors.New("JNIGI: detachCurrentThread error")
}
return nil
}
// Destroy calls JNI DestroyJavaVM
func (j *JVM) Destroy() error {
if destroyJavaVM(j.javaVM) < 0 {
return errors.New("JNIGI: destroyJavaVM error")
}
return nil
}
// GetJVM Calls JNI GetJavaVM. Needs to be called on an attached thread.
func (j *Env) GetJVM() (*JVM, error) {
p := malloc(unsafe.Sizeof((unsafe.Pointer)(nil)))
if getJavaVM(j.jniEnv, p) < 0 {
return nil, errors.New("Couldn't get JVM")
}
jvm := &JVM{javaVM: *(*unsafe.Pointer)(p), addtlClassLoader: j.addtlClassLoader}
free(p)
return jvm, nil
}
func (j *Env) exceptionCheck() bool {
return toBool(exceptionCheck(j.jniEnv))
}
func (j *Env) describeException() {
exceptionDescribe(j.jniEnv)
}
func (j *Env) handleException() error {
e := exceptionOccurred(j.jniEnv)
if e == 0 {
return errors.New("Java JNI function returned error but JNI indicates no current exception")
}
defer deleteLocalRef(j.jniEnv, jobject(e))
ref := WrapJObject(uintptr(e), "java/lang/Throwable", false)
if j.ExceptionHandler == nil {
return DefaultExceptionHandler.CatchException(j, ref)
}
// Temporarily disable handler in the event exception rises during handling.
// By setting it to the DescribeExceptionHandler, exceptions will get printed
// and cleared.
handler := j.ExceptionHandler
j.ExceptionHandler = DescribeExceptionHandler
defer func() {
j.ExceptionHandler = handler
}()
return handler.CatchException(j, ref)
}
// NewObject calls JNI NewObjectA, className class name of new object, args arguments to constructor.
func (j *Env) NewObject(className string, args ...interface{}) (*ObjectRef, error) {
class, err := j.callFindClass(className)
if err != nil {
return nil, err
}
if err := replaceConvertedArgs(args); err != nil {
return nil, err
}
var methodSig string
if j.preCalcSig != "" {
methodSig = j.preCalcSig
j.preCalcSig = ""
} else {
calcSig, err := sigForMethod(Void, "", args)
if err != nil {
return nil, err
}
methodSig = calcSig
}
mid, err := j.callGetMethodID(false, class, "<init>", methodSig)
if err != nil {
return nil, err
}
// create args for jni call
jniArgs, refs, err := j.createArgs(args)
if err != nil {
return nil, err
}
defer func() {
cleanUpArgs(jniArgs)
for _, ref := range refs {
deleteLocalRef(j.jniEnv, ref)
}
}()
obj := newObjectA(j.jniEnv, class, mid, jniArgs)
if obj == 0 {
return nil, j.handleException()
}
return &ObjectRef{obj, className, false}, nil
}
// FindCLass returns reference to java/lang/Class
// Argument is className of target class
func (j *Env) FindClass(className string) (*ObjectRef, error) {
class, err := j.callFindClass(className)
if err != nil {
return nil, err
}
return &ObjectRef{jobject(class), "java/lang/Class", false}, nil
}
func (j *Env) callFindClass(className string) (jclass, error) {
if v, ok := j.classCache[className]; ok {
return v, nil
}
cnCstr := cString(className)
defer free(cnCstr)
class := findClass(j.jniEnv, cnCstr, j.addtlClassLoader)
if class == 0 {
return 0, j.handleException()
}
ref := newGlobalRef(j.jniEnv, jobject(class))
deleteLocalRef(j.jniEnv, jobject(class))
j.classCache[className] = jclass(ref)
return jclass(ref), nil
}
func (j *Env) callGetMethodID(static bool, class jclass, name, sig string) (jmethodID, error) {
mnCstr := cString(name)
defer free(mnCstr)
sigCstr := cString(sig)
defer free(sigCstr)
var mid jmethodID
if static {
mid = getStaticMethodID(j.jniEnv, class, mnCstr, sigCstr)
} else {
mid = getMethodID(j.jniEnv, class, mnCstr, sigCstr)
}
// fmt.Printf("sig = %s\n", sig)
if mid == 0 {
return 0, j.handleException()
}
return mid, nil
}
// PrecalculateSignature sets the signature of the next call to sig, disables automatic signature building.
func (j *Env) PrecalculateSignature(sig string) {
j.preCalcSig = sig
}
const big = 1024 * 1024 * 100
// FromObjectArray converts an Java array of objects objRef in to a slice of *ObjectRef which is returned.
func (j *Env) FromObjectArray(objRef *ObjectRef) []*ObjectRef {
len := int(getArrayLength(j.jniEnv, jarray(objRef.jobject)))
// exception check?
v := make([]*ObjectRef, len)
for i := 0; i < len; i++ {
jobj := getObjectArrayElement(j.jniEnv, jobjectArray(objRef.jobject), jsize(i))
if j.exceptionCheck() {
panic(j.handleException())
}
v[i] = &ObjectRef{jobj, objRef.className, false}
}
return v
}
func (j *Env) toGoArray(array jobject, aType Type) (interface{}, error) {
len := int(getArrayLength(j.jniEnv, jarray(array)))
// exception check?
switch aType.baseType() {
case Boolean:
v := make([]bool, len)
if len >= 0 {
ptr := getBooleanArrayElements(j.jniEnv, jbooleanArray(array), nil)
if j.exceptionCheck() {
return nil, j.handleException()
}
elems := (*(*[big]byte)(ptr))[0:len]
for i := 0; i < len; i++ {
v[i] = (elems[i] == 1)
}
releaseBooleanArrayElements(j.jniEnv, jbooleanArray(array), ptr, jint(jni_abort))
}
return v, nil
case Byte:
v := make([]byte, len)
if len >= 0 {
ptr := getByteArrayElements(j.jniEnv, jbyteArray(array), nil)
if j.exceptionCheck() {
return nil, j.handleException()
}
elems := (*(*[big]byte)(ptr))[0:len]
copy(v, elems)
releaseByteArrayElements(j.jniEnv, jbyteArray(array), ptr, jint(jni_abort))
}
return v, nil
case Short:
v := make([]int16, len)
if len >= 0 {
ptr := getShortArrayElements(j.jniEnv, jshortArray(array), nil)
if j.exceptionCheck() {
return nil, j.handleException()
}
elems := (*(*[big]int16)(ptr))[0:len]
copy(v, elems)
releaseShortArrayElements(j.jniEnv, jshortArray(array), ptr, jint(jni_abort))
}
return v, nil
case Char:
v := make([]uint16, len)
if len >= 0 {
ptr := getCharArrayElements(j.jniEnv, jcharArray(array), nil)
if j.exceptionCheck() {
return nil, j.handleException()
}
elems := (*(*[big]uint16)(ptr))[0:len]
copy(v, elems)
releaseCharArrayElements(j.jniEnv, jcharArray(array), ptr, jint(jni_abort))
}
return v, nil
case Int:
v := make([]int, len)
if len >= 0 {
ptr := getIntArrayElements(j.jniEnv, jintArray(array), nil)
if j.exceptionCheck() {
return nil, j.handleException()
}
elems := (*(*[big]int32)(ptr))[0:len]
//copy(v, elems)
for i := 0; i < len; i++ {
v[i] = int(elems[i])
}
releaseIntArrayElements(j.jniEnv, jintArray(array), ptr, jint(jni_abort))
}
return v, nil
case Long:
v := make([]int64, len)
if len >= 0 {
ptr := getLongArrayElements(j.jniEnv, jlongArray(array), nil)
if j.exceptionCheck() {
return nil, j.handleException()
}
elems := (*(*[big]int64)(ptr))[0:len]
copy(v, elems)
releaseLongArrayElements(j.jniEnv, jlongArray(array), ptr, jint(jni_abort))
}
return v, nil
case Float:
v := make([]float32, len)
if len >= 0 {
ptr := getFloatArrayElements(j.jniEnv, jfloatArray(array), nil)
if j.exceptionCheck() {
return nil, j.handleException()
}
elems := (*(*[big]float32)(ptr))[0:len]
copy(v, elems)
releaseFloatArrayElements(j.jniEnv, jfloatArray(array), ptr, jint(jni_abort))
}
return v, nil
case Double:
v := make([]float64, len)
if len >= 0 {
ptr := getDoubleArrayElements(j.jniEnv, jdoubleArray(array), nil)
if j.exceptionCheck() {
return nil, j.handleException()
}
elems := (*(*[big]float64)(ptr))[0:len]
copy(v, elems)
releaseDoubleArrayElements(j.jniEnv, jdoubleArray(array), ptr, jint(jni_abort))
}
return v, nil
default:
return nil, errors.New("JNIGI unsupported array type")
}
}
// ToObjectArray converts slice of ObjectRef objRefs of class name className, to a new Java object
// array returning a reference to this array.
func (j *Env) ToObjectArray(objRefs []*ObjectRef, className string) (arrayRef *ObjectRef) {
arrayRef = &ObjectRef{className: className, isArray: true}
class, err := j.callFindClass(className)
if err != nil {
j.describeException()
exceptionClear(j.jniEnv)
return
}
oa := newObjectArray(j.jniEnv, jsize(len(objRefs)), class, 0)
if oa == 0 {
panic(j.handleException())
}
arrayRef.jobject = jobject(oa)
for i, obj := range objRefs {
setObjectArrayElement(j.jniEnv, oa, jsize(i), obj.jobject)
if j.exceptionCheck() {
j.describeException()
exceptionClear(j.jniEnv)
}
}
return
}
// ByteArray holds a JNI JbyteArray
type ByteArray struct {
arr jbyteArray
n int
}
// NewByteArray calls JNI NewByteArray
func (j *Env) NewByteArray(n int) *ByteArray {
a := newByteArray(j.jniEnv, jsize(n))
return &ByteArray{a, n}
}
// NewByteArrayFromSlice calls JNI NewByteArray and GetCritical, copies src to byte array,
// calls JNI Release Critical. Returns new byte array.
func (j *Env) NewByteArrayFromSlice(src []byte) *ByteArray {
b := j.NewByteArray(len(src))
if len(src) > 0 {
bytes := b.GetCritical(j)
copy(bytes, src)
b.ReleaseCritical(j, bytes)
}
return b
}
// NewByteArrayFromObject creates new ByteArray and sets it from ObjectRef o.
func (j *Env) NewByteArrayFromObject(o *ObjectRef) *ByteArray {
ba := &ByteArray{}
ba.SetObject(o)
ba.n = int(getArrayLength(j.jniEnv, jarray(ba.arr)))
return ba
}
func (b *ByteArray) jobj() jobject {
return jobject(b.arr)
}
func (b *ByteArray) getType() Type {
return Byte | Array
}
// GetCritical calls JNI GetPrimitiveArrayCritical
func (b *ByteArray) GetCritical(env *Env) []byte {
if b.n == 0 {
return nil
}
ptr := getPrimitiveArrayCritical(env.jniEnv, jarray(b.arr), nil)
return (*(*[big]byte)(ptr))[0:b.n]
}
// GetCritical calls JNI ReleasePrimitiveArrayCritical
func (b *ByteArray) ReleaseCritical(env *Env, bytes []byte) {
if len(bytes) == 0 {
return
}
ptr := unsafe.Pointer(&bytes[0])
releasePrimitiveArrayCritical(env.jniEnv, jarray(b.arr), ptr, 0)
}
// GetObject returns byte array as *ObjectRef.
func (b *ByteArray) GetObject() *ObjectRef {
return &ObjectRef{jobject(b.arr), "java/lang/Object", false}
}
// SetObject sets byte array from o.
func (b *ByteArray) SetObject(o *ObjectRef) {
b.arr = jbyteArray(o.jobject)
}
// CopyBytes creates a go slice of bytes of same length as byte array, calls GetCritical,
// copies byte array into go slice, calls ReleaseCritical, returns go slice.
func (b *ByteArray) CopyBytes(env *Env) []byte {
r := make([]byte, b.n)
src := b.GetCritical(env)
copy(r, src)
b.ReleaseCritical(env, src)
return r
}
// this copies slice contents in to C memory before passing this pointer to JNI array function
// if copy var is set to true
func (j *Env) toJavaArray(src interface{}) (jobject, error) {
switch v := src.(type) {
case []bool:
ba := newBooleanArray(j.jniEnv, jsize(len(v)))
if ba == 0 {
return 0, j.handleException()
}
if len(v) == 0 {
return jobject(ba), nil
}
src := make([]byte, len(v))
for i, vset := range v {
if vset {
src[i] = 1
}
}
var ptr unsafe.Pointer
if copyToC {
ptr = malloc(uintptr(len(v)))
defer free(ptr)
data := (*(*[big]byte)(ptr))[:len(v)]
copy(data, src)
} else {
ptr = unsafe.Pointer(&src[0])
}
setBooleanArrayRegion(j.jniEnv, ba, jsize(0), jsize(len(v)), ptr)
if j.exceptionCheck() {
return 0, j.handleException()
}
return jobject(ba), nil
case []byte:
ba := newByteArray(j.jniEnv, jsize(len(v)))
if ba == 0 {
return 0, j.handleException()
}
if len(v) == 0 {
return jobject(ba), nil
}
var ptr unsafe.Pointer
if copyToC {
ptr = malloc(uintptr(len(v)))
defer free(ptr)
data := (*(*[big]byte)(ptr))[:len(v)]
copy(data, v)
} else {
ptr = unsafe.Pointer(&v[0])
}
setByteArrayRegion(j.jniEnv, ba, jsize(0), jsize(len(v)), ptr)
if j.exceptionCheck() {
return 0, j.handleException()
}
return jobject(ba), nil
case []int16:
array := newShortArray(j.jniEnv, jsize(len(v)))
if array == 0 {
return 0, j.handleException()
}
if len(v) == 0 {
return jobject(array), nil
}
var ptr unsafe.Pointer
if copyToC {
ptr = malloc(unsafe.Sizeof(int16(0)) * uintptr(len(v)))
defer free(ptr)
data := (*(*[big]int16)(ptr))[:len(v)]
copy(data, v)
} else {
ptr = unsafe.Pointer(&v[0])
}
setShortArrayRegion(j.jniEnv, array, jsize(0), jsize(len(v)), ptr)
if j.exceptionCheck() {
return 0, j.handleException()
}
return jobject(array), nil
case []uint16:
array := newCharArray(j.jniEnv, jsize(len(v)))
if array == 0 {
return 0, j.handleException()
}
if len(v) == 0 {
return jobject(array), nil
}
var ptr unsafe.Pointer
if copyToC {
ptr = malloc(unsafe.Sizeof(uint16(0)) * uintptr(len(v)))
defer free(ptr)
data := (*(*[big]uint16)(ptr))[:len(v)]
copy(data, v)
} else {
ptr = unsafe.Pointer(&v[0])
}
setCharArrayRegion(j.jniEnv, array, jsize(0), jsize(len(v)), ptr)
if j.exceptionCheck() {
return 0, j.handleException()
}
return jobject(array), nil
case []int32:
array := newIntArray(j.jniEnv, jsize(len(v)))
if array == 0 {
return 0, j.handleException()
}
if len(v) == 0 {
return jobject(array), nil
}
var ptr unsafe.Pointer
if copyToC {
ptr = malloc(unsafe.Sizeof(int32(0)) * uintptr(len(v)))
defer free(ptr)
data := (*(*[big]int32)(ptr))[:len(v)]
copy(data, v)
} else {
ptr = unsafe.Pointer(&v[0])
}
setIntArrayRegion(j.jniEnv, array, jsize(0), jsize(len(v)), ptr)
if j.exceptionCheck() {
return 0, j.handleException()
}
return jobject(array), nil
case []int:
array := newIntArray(j.jniEnv, jsize(len(v)))
if array == 0 {
return 0, j.handleException()
}
if len(v) == 0 {
return jobject(array), nil
}
var ptr unsafe.Pointer
if copyToC {
ptr = malloc(unsafe.Sizeof(int32(0)) * uintptr(len(v)))
defer free(ptr)
data := (*(*[big]int32)(ptr))[:len(v)]
//copy(data, v)
for i := 0; i < len(data); i++ {
data[i] = int32(v[i])
}
} else {
data := make([]int32, len(v))
for i := 0; i < len(v); i++ {
data[i] = int32(v[i])
}
ptr = unsafe.Pointer(&data[0])
}
setIntArrayRegion(j.jniEnv, array, jsize(0), jsize(len(v)), ptr)
if j.exceptionCheck() {
return 0, j.handleException()
}
return jobject(array), nil
case []int64:
array := newLongArray(j.jniEnv, jsize(len(v)))
if array == 0 {
return 0, j.handleException()
}
if len(v) == 0 {
return jobject(array), nil
}
var ptr unsafe.Pointer
if copyToC {
ptr = malloc(unsafe.Sizeof(int64(0)) * uintptr(len(v)))
defer free(ptr)
data := (*(*[big]int64)(ptr))[:len(v)]
copy(data, v)
} else {
ptr = unsafe.Pointer(&v[0])
}
setLongArrayRegion(j.jniEnv, array, jsize(0), jsize(len(v)), ptr)
if j.exceptionCheck() {
return 0, j.handleException()
}
return jobject(array), nil
case []float32:
array := newFloatArray(j.jniEnv, jsize(len(v)))
if array == 0 {
return 0, j.handleException()
}
if len(v) == 0 {
return jobject(array), nil
}
var ptr unsafe.Pointer
if copyToC {
ptr = malloc(unsafe.Sizeof(float32(0)) * uintptr(len(v)))
defer free(ptr)
data := (*(*[big]float32)(ptr))[:len(v)]
copy(data, v)
} else {
ptr = unsafe.Pointer(&v[0])
}
setFloatArrayRegion(j.jniEnv, array, jsize(0), jsize(len(v)), ptr)
if j.exceptionCheck() {
return 0, j.handleException()
}
return jobject(array), nil
case []float64:
array := newDoubleArray(j.jniEnv, jsize(len(v)))
if array == 0 {
return 0, j.handleException()
}
if len(v) == 0 {
return jobject(array), nil
}
var ptr unsafe.Pointer
if copyToC {
ptr = malloc(unsafe.Sizeof(float64(0)) * uintptr(len(v)))
defer free(ptr)
data := (*(*[big]float64)(ptr))[:len(v)]
copy(data, v)
} else {
ptr = unsafe.Pointer(&v[0])
}
setDoubleArrayRegion(j.jniEnv, array, jsize(0), jsize(len(v)), ptr)
if j.exceptionCheck() {
return 0, j.handleException()
}
return jobject(array), nil
default:
return 0, errors.New("JNIGI unsupported array type")
}
}
// pointer should be freed, refs should be deleted
// jvalue 64 bit
func (j *Env) createArgs(args []interface{}) (ptr unsafe.Pointer, refs []jobject, err error) {
if len(args) == 0 {
return nil, nil, nil
}
argList := make([]uint64, len(args))
refs = make([]jobject, 0)
for i, arg := range args {
switch v := arg.(type) {
case *convertedArg:
argList[i] = uint64(v.ObjectRef.jobject)
refs = append(refs, v.ObjectRef.jobject)
case jobj:
argList[i] = uint64(v.jobj())
case bool:
if v {
argList[i] = uint64(jboolean(1))
} else {
argList[i] = uint64(jboolean(0))
}
case byte:
argList[i] = uint64(jbyte(v))
case uint16:
argList[i] = uint64(jchar(v))
case int16:
argList[i] = uint64(jshort(v))
case int32:
argList[i] = uint64(jint(v))
case int:
argList[i] = uint64(jint(int32(v)))
case int64:
argList[i] = uint64(jlong(v))
case float32:
argList[i] = uint64(jfloat(v))
case float64:
argList[i] = uint64(jdouble(v))
case []bool, []byte, []int16, []uint16, []int32, []int, []int64, []float32, []float64:
if array, arrayErr := j.toJavaArray(v); arrayErr == nil {
argList[i] = uint64(array)
refs = append(refs, array)
} else {
err = arrayErr
}
default:
err = fmt.Errorf("JNIGI: argument not a valid value %T (%v)", args[i], args[i])
}
if err != nil {
break
}
}
if err != nil {
for _, ref := range refs {
deleteLocalRef(j.jniEnv, ref)
}
refs = nil
return
}
if copyToC {
ptr = malloc(unsafe.Sizeof(uint64(0)) * uintptr(len(args)))
data := (*(*[big]uint64)(ptr))[:len(args)]
copy(data, argList)
} else {
ptr = unsafe.Pointer(&argList[0])
}
return
}
// TypeSpec is implemented by Type, ObjectType and ObjectArrayType.
type TypeSpec interface {
internal()
}
// Type is used to specify return types and field types. Array value can be ORed with primitive type.
// Implements TypeSpec. See package constants for values.
type Type uint32
const (
Void = Type(1 << iota)
Boolean
Byte
Char
Short
Int
Long
Float
Double
Object
Array
)
func (t Type) baseType() Type {
return t &^ Array
}
func (t Type) isArray() bool {
return t&Array > 0
}
func (t Type) internal() {}
// ObjectType is treated as Object Type. It's value is used to specify the class of the object.
// For example jnigi.ObjectType("java/lang/string").
// Implements TypeSpec.
type ObjectType string
func (o ObjectType) internal() {}
// ObjectArrayType is treated as Object | Array Type. It's value specify the class of the elements.
// Implements TypeSpec.
type ObjectArrayType string
func (o ObjectArrayType) internal() {}
type convertedArray interface {
getType() Type
}
// Allow return types to be a string that specifies an object type. This is to
// retain compatiblity.
func typeOfReturnValue(value interface{}) (t Type, className string, err error) {
if v, ok := value.(string); ok {
return typeOfValue(ObjectType(v))
}
return typeOfValue(value)
}
// ClassInfoGetter is implemented by *ObjectRef, *CastedObjectRef to get type info for object values.
type ClassInfoGetter interface {
GetClassName() string
IsArray() bool
}
// TypeGetter can be implemented to control which primitive type a value is treated as.
type TypeGetter interface {
GetType() Type
}
func typeOfValue(value interface{}) (t Type, className string, err error) {
switch v := value.(type) {
case Type:
t = v
if t.baseType() == Object {
className = "java/lang/Object"