/
CallbackReference.java
798 lines (736 loc) · 31.2 KB
/
CallbackReference.java
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
/* Copyright (c) 2007-2013 Timothy Wall, All Rights Reserved
*
* The contents of this file is dual-licensed under 2
* alternative Open Source/Free licenses: LGPL 2.1 or later and
* Apache License 2.0. (starting with JNA version 4.0.0).
*
* You can freely decide which license you want to apply to
* the project.
*
* You may obtain a copy of the LGPL License at:
*
* http://www.gnu.org/licenses/licenses.html
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "LGPL2.1".
*
* You may obtain a copy of the Apache License at:
*
* http://www.apache.org/licenses/
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "AL2.0".
*/
package com.sun.jna;
import com.sun.jna.internal.Cleaner;
import java.io.Closeable;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
/**
* Provides a reference to an association between a native callback closure
* and a Java {@link Callback} closure.
*/
public class CallbackReference extends WeakReference<Callback> implements Closeable {
// Access to callbackMap, directCallbackMap, pointerCallbackMap is protected
// by synchonizing on pointerCallbackMap
static final Map<Callback, CallbackReference> callbackMap = new WeakHashMap<>();
static final Map<Callback, CallbackReference> directCallbackMap = new WeakHashMap<>();
//callbacks with different signatures sharing the same pointer
static final Map<Pointer, Reference<Callback>[]> pointerCallbackMap = new WeakHashMap<>();
// Track memory allocations associated with this closure (usually String args)
static final Map<Object, Object> allocations =
Collections.synchronizedMap(new WeakHashMap<>());
// Global map of allocated closures to facilitate centralized cleanup
private static final Map<Long, Reference<CallbackReference>> allocatedMemory =
new ConcurrentHashMap<>();
private static final Method PROXY_CALLBACK_METHOD;
static {
try {
PROXY_CALLBACK_METHOD = CallbackProxy.class.getMethod("callback", new Class[] { Object[].class });
} catch(Exception e) {
throw new Error("Error looking up CallbackProxy.callback() method");
}
}
private static final Class<?> DLL_CALLBACK_CLASS;
static {
if (Platform.isWindows()) {
try {
DLL_CALLBACK_CLASS = Class.forName("com.sun.jna.win32.DLLCallback");
} catch(ClassNotFoundException e) {
throw new Error("Error loading DLLCallback class", e);
}
} else {
DLL_CALLBACK_CLASS = null;
}
}
private static final Map<Callback, CallbackThreadInitializer> initializers = new WeakHashMap<>();
/**
* @param cb The {@link Callback} instance
* @param initializer The {@link CallbackThreadInitializer} - if {@code null} then the
* associated initializer instance is removed
* @return The previous initializer instance (may be {@code null})
*/
static CallbackThreadInitializer setCallbackThreadInitializer(Callback cb, CallbackThreadInitializer initializer) {
synchronized(initializers) {
if (initializer != null) {
return initializers.put(cb, initializer);
} else {
return initializers.remove(cb);
}
}
}
static class AttachOptions extends Structure {
public static final List<String> FIELDS = createFieldsOrder("daemon", "detach", "name");
public boolean daemon;
public boolean detach;
public String name;
// Thread name must be UTF8-encoded
{
setStringEncoding("utf8");
}
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
/* Called from native code to initialize a callback thread. */
private static ThreadGroup initializeThread(Callback cb, AttachOptions args) {
CallbackThreadInitializer init = null;
if (cb instanceof DefaultCallbackProxy) {
cb = ((DefaultCallbackProxy)cb).getCallback();
}
synchronized(initializers) {
init = initializers.get(cb);
}
ThreadGroup group = null;
if (init != null) {
group = init.getThreadGroup(cb);
args.name = init.getName(cb);
args.daemon = init.isDaemon(cb);
args.detach = init.detach(cb);
args.write();
}
return group;
}
/** Return a Callback associated with the given function pointer.
* If the pointer refers to a Java callback trampoline, return the original
* Java Callback. Otherwise, return a proxy to the native function
* pointer.
* @throws IllegalStateException if the given pointer has already been
* mapped to a callback of a different type.
*/
public static Callback getCallback(Class<?> type, Pointer p) {
return getCallback(type, p, false);
}
private static Callback getCallback(Class<?> type, Pointer p, boolean direct) {
if (p == null) {
return null;
}
if (!type.isInterface())
throw new IllegalArgumentException("Callback type must be an interface");
Map<Callback, CallbackReference> map = direct ? directCallbackMap : callbackMap;
synchronized(pointerCallbackMap) {
Reference<Callback>[] array = pointerCallbackMap.get(p);
Callback cb = getTypeAssignableCallback(type, array);
if (cb != null) {
return cb;
}
cb = createCallback(type, p);
pointerCallbackMap.put(p, addCallbackToArray(cb,array));
// No CallbackReference for this callback
map.remove(cb);
return cb;
}
}
private static Callback getTypeAssignableCallback(Class<?> type, Reference<Callback>[] array) {
if (array != null) {
for (int i=0;i < array.length;i++) {
Callback cb = array[i].get();
if (cb != null && type.isAssignableFrom(cb.getClass())) {
return cb;
}
}
}
return null;
}
private static Reference<Callback>[] addCallbackToArray(Callback cb,Reference<Callback>[] array) {
int reqArraySize = 1; //space for the new item
if (array != null) {
//drop any freed reference
for (int i=0;i < array.length;i++) {
if( array[i].get() == null ) {
array[i] = null;
}
else {
reqArraySize++;
}
}
}
@SuppressWarnings( "unchecked" )
Reference<Callback>[] newArray = new Reference[reqArraySize];
int nidx=0;
if (array != null) {
//shift items if needed
for (int i=0;i < array.length;i++) {
if (array[i] != null) {
newArray[nidx++] = array[i];
}
}
}
newArray[nidx] = new WeakReference<>(cb);
return newArray;
}
private static Callback createCallback(Class<?> type, Pointer p) {
int ctype = AltCallingConvention.class.isAssignableFrom(type)
? Function.ALT_CONVENTION : Function.C_CONVENTION;
Map<String, Object> foptions = new HashMap<>(Native.getLibraryOptions(type));
foptions.put(Function.OPTION_INVOKING_METHOD, getCallbackMethod(type));
NativeFunctionHandler h = new NativeFunctionHandler(p, ctype, foptions);
return (Callback)Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type }, h);
}
Cleaner.Cleanable cleanable;
Pointer cbstruct;
Pointer trampoline;
// Keep a reference to the proxy to avoid premature GC of it
CallbackProxy proxy;
Method method;
int callingConvention;
private CallbackReference(Callback callback, int callingConvention, boolean direct) {
super(callback);
TypeMapper mapper = Native.getTypeMapper(callback.getClass());
this.callingConvention = callingConvention;
Class<?>[] nativeParamTypes;
Class<?> returnType;
// Check whether direct mapping may be used, or whether
// we need to fall back to conventional mapping
boolean ppc = Platform.isPPC();
if (direct) {
Method m = getCallbackMethod(callback);
Class<?>[] ptypes = m.getParameterTypes();
for (int i=0;i < ptypes.length;i++) {
// varargs w/FP args via ffi_call fails on ppc (darwin)
if (ppc && (ptypes[i] == float.class
|| ptypes[i] == double.class)) {
direct = false;
break;
}
// Direct mode callbacks do not support TypeMapper
if (mapper != null
&& mapper.getFromNativeConverter(ptypes[i]) != null) {
direct = false;
break;
}
}
// Direct mode callbacks do not support TypeMapper
if (mapper != null
&& mapper.getToNativeConverter(m.getReturnType()) != null) {
direct = false;
}
}
String encoding = Native.getStringEncoding(callback.getClass());
long peer = 0;
if (direct) {
method = getCallbackMethod(callback);
nativeParamTypes = method.getParameterTypes();
returnType = method.getReturnType();
int flags = Native.CB_OPTION_DIRECT;
if (DLL_CALLBACK_CLASS != null
&& DLL_CALLBACK_CLASS.isInstance(callback)) {
flags |= Native.CB_OPTION_IN_DLL;
}
peer = Native.createNativeCallback(callback, method,
nativeParamTypes, returnType,
callingConvention, flags,
encoding);
} else {
if (callback instanceof CallbackProxy) {
proxy = (CallbackProxy)callback;
}
else {
proxy = new DefaultCallbackProxy(getCallbackMethod(callback), mapper, encoding);
}
nativeParamTypes = proxy.getParameterTypes();
returnType = proxy.getReturnType();
// Generate a list of parameter types that the native code can
// handle. Let the CallbackProxy do any further conversion
// to match the true Java callback method signature
if (mapper != null) {
for (int i=0;i < nativeParamTypes.length;i++) {
FromNativeConverter rc = mapper.getFromNativeConverter(nativeParamTypes[i]);
if (rc != null) {
nativeParamTypes[i] = rc.nativeType();
}
}
ToNativeConverter tn = mapper.getToNativeConverter(returnType);
if (tn != null) {
returnType = tn.nativeType();
}
}
for (int i=0;i < nativeParamTypes.length;i++) {
nativeParamTypes[i] = getNativeType(nativeParamTypes[i]);
if (!isAllowableNativeType(nativeParamTypes[i])) {
String msg = "Callback argument " + nativeParamTypes[i]
+ " requires custom type conversion";
throw new IllegalArgumentException(msg);
}
}
returnType = getNativeType(returnType);
if (!isAllowableNativeType(returnType)) {
String msg = "Callback return type " + returnType
+ " requires custom type conversion";
throw new IllegalArgumentException(msg);
}
int flags = DLL_CALLBACK_CLASS != null
&& DLL_CALLBACK_CLASS.isInstance(callback)
? Native.CB_OPTION_IN_DLL : 0;
peer = Native.createNativeCallback(proxy, PROXY_CALLBACK_METHOD,
nativeParamTypes, returnType,
callingConvention, flags,
encoding);
}
cbstruct = peer != 0 ? new Pointer(peer) : null;
if(peer != 0) {
allocatedMemory.put(peer, new WeakReference<>(this));
cleanable = Cleaner.getCleaner().register(this, new CallbackReferenceDisposer(cbstruct));
}
}
private Class<?> getNativeType(Class<?> cls) {
if (Structure.class.isAssignableFrom(cls)) {
// Make sure we can instantiate an argument of this type
Structure.validate((Class<? extends Structure>)cls);
if (!Structure.ByValue.class.isAssignableFrom(cls))
return Pointer.class;
} else if (NativeMapped.class.isAssignableFrom(cls)) {
return NativeMappedConverter.getInstance(cls).nativeType();
} else if (cls == String.class
|| cls == WString.class
|| cls == String[].class
|| cls == WString[].class
|| Callback.class.isAssignableFrom(cls)) {
return Pointer.class;
}
return cls;
}
private static Method checkMethod(Method m) {
if (m.getParameterTypes().length > Function.MAX_NARGS) {
String msg = "Method signature exceeds the maximum "
+ "parameter count: " + m;
throw new UnsupportedOperationException(msg);
}
return m;
}
/*
* Find the first instance of an interface which implements the Callback
* interface or an interface derived from Callback, which defines an
* appropriate callback method.
*/
static Class<?> findCallbackClass(Class<?> type) {
if (!Callback.class.isAssignableFrom(type)) {
throw new IllegalArgumentException(type.getName() + " is not derived from com.sun.jna.Callback");
}
if (type.isInterface()) {
return type;
}
Class<?>[] ifaces = type.getInterfaces();
for (int i=0;i < ifaces.length;i++) {
if (Callback.class.isAssignableFrom(ifaces[i])) {
try {
// Make sure it's got a recognizable callback method
getCallbackMethod(ifaces[i]);
return ifaces[i];
}
catch(IllegalArgumentException e) {
break;
}
}
}
if (Callback.class.isAssignableFrom(type.getSuperclass())) {
return findCallbackClass(type.getSuperclass());
}
return type;
}
private static Method getCallbackMethod(Callback callback) {
return getCallbackMethod(findCallbackClass(callback.getClass()));
}
private static Method getCallbackMethod(Class<?> cls) {
// Look at only public methods defined by the Callback class
Method[] pubMethods = cls.getDeclaredMethods();
Method[] classMethods = cls.getMethods();
Set<Method> pmethods = new HashSet<>(Arrays.asList(pubMethods));
pmethods.retainAll(Arrays.asList(classMethods));
// Remove Object methods disallowed as callback method names
for (Iterator<Method> i=pmethods.iterator();i.hasNext();) {
Method m = i.next();
if (Callback.FORBIDDEN_NAMES.contains(m.getName())) {
i.remove();
}
}
Method[] methods = pmethods.toArray(new Method[0]);
if (methods.length == 1) {
return checkMethod(methods[0]);
}
for (int i=0;i < methods.length;i++) {
Method m = methods[i];
if (Callback.METHOD_NAME.equals(m.getName())) {
return checkMethod(m);
}
}
String msg = "Callback must implement a single public method, "
+ "or one public method named '" + Callback.METHOD_NAME + "'";
throw new IllegalArgumentException(msg);
}
/** Set the behavioral options for this callback. */
private void setCallbackOptions(int options) {
cbstruct.setInt(Native.POINTER_SIZE, options);
}
/** Obtain a pointer to the native glue code for this callback. */
public Pointer getTrampoline() {
if (trampoline == null) {
trampoline = cbstruct.getPointer(0);
}
return trampoline;
}
/** Free native resources associated with this callback. */
public void close() {
if (cleanable != null) {
cleanable.clean();
}
cbstruct = null;
}
@Deprecated
protected void dispose() {
close();
}
/** Dispose of all memory allocated for callbacks. */
static void disposeAll() {
// use a copy since dispose() modifes the map
Collection<Reference<CallbackReference>> refs = new LinkedList<>(allocatedMemory.values());
for (Reference<CallbackReference> r : refs) {
CallbackReference ref = r.get();
if(ref != null) {
ref.close();
}
}
}
private Callback getCallback() {
return get();
}
/** If the callback is one we generated to wrap a native function pointer,
return that. Otherwise return null.
*/
private static Pointer getNativeFunctionPointer(Callback cb) {
if (Proxy.isProxyClass(cb.getClass())) {
Object handler = Proxy.getInvocationHandler(cb);
if (handler instanceof NativeFunctionHandler) {
return ((NativeFunctionHandler)handler).getPointer();
}
}
return null;
}
/** Return a {@link Pointer} to the native function address for the
* given callback.
*/
public static Pointer getFunctionPointer(Callback cb) {
return getFunctionPointer(cb, false);
}
/** Native code may call this method with direct=true. */
private static Pointer getFunctionPointer(Callback cb, boolean direct) {
Pointer fp = null;
if (cb == null) {
return null;
}
if ((fp = getNativeFunctionPointer(cb)) != null) {
return fp;
}
Map<String, ?> options = Native.getLibraryOptions(cb.getClass());
int callingConvention = cb instanceof AltCallingConvention
? Function.ALT_CONVENTION
: (options != null && options.containsKey(Library.OPTION_CALLING_CONVENTION)
? ((Integer)options.get(Library.OPTION_CALLING_CONVENTION)).intValue()
: Function.C_CONVENTION);
Map<Callback, CallbackReference> map = direct ? directCallbackMap : callbackMap;
synchronized(pointerCallbackMap) {
CallbackReference cbref = map.get(cb);
if (cbref == null || cbref.cbstruct == null) {
cbref = new CallbackReference(cb, callingConvention, direct);
map.put(cb, cbref);
pointerCallbackMap.put(cbref.getTrampoline(),
addCallbackToArray(cb, null));
if (initializers.containsKey(cb)) {
cbref.setCallbackOptions(Native.CB_HAS_INITIALIZER);
}
}
return cbref.getTrampoline();
}
}
private class DefaultCallbackProxy implements CallbackProxy {
private final Method callbackMethod;
private ToNativeConverter toNative;
private final FromNativeConverter[] fromNative;
private final String encoding;
public DefaultCallbackProxy(Method callbackMethod, TypeMapper mapper, String encoding) {
this.callbackMethod = callbackMethod;
this.encoding = encoding;
Class<?>[] argTypes = callbackMethod.getParameterTypes();
Class<?> returnType = callbackMethod.getReturnType();
fromNative = new FromNativeConverter[argTypes.length];
if (NativeMapped.class.isAssignableFrom(returnType)) {
toNative = NativeMappedConverter.getInstance(returnType);
}
else if (mapper != null) {
toNative = mapper.getToNativeConverter(returnType);
}
for (int i=0;i < fromNative.length;i++) {
if (NativeMapped.class.isAssignableFrom(argTypes[i])) {
fromNative[i] = new NativeMappedConverter(argTypes[i]);
}
else if (mapper != null) {
fromNative[i] = mapper.getFromNativeConverter(argTypes[i]);
}
}
if (!callbackMethod.isAccessible()) {
try {
callbackMethod.setAccessible(true);
}
catch(SecurityException e) {
throw new IllegalArgumentException("Callback method is inaccessible, make sure the interface is public: " + callbackMethod);
}
}
}
public Callback getCallback() {
return CallbackReference.this.getCallback();
}
private Object invokeCallback(Object[] args) {
Class<?>[] paramTypes = callbackMethod.getParameterTypes();
Object[] callbackArgs = new Object[args.length];
// convert basic supported types to appropriate Java parameter types
for (int i=0;i < args.length;i++) {
Class<?> type = paramTypes[i];
Object arg = args[i];
if (fromNative[i] != null) {
FromNativeContext context =
new CallbackParameterContext(type, callbackMethod, args, i);
callbackArgs[i] = fromNative[i].fromNative(arg, context);
} else {
callbackArgs[i] = convertArgument(arg, type);
}
}
Object result = null;
Callback cb = DefaultCallbackProxy.this.getCallback();
if (cb != null) {
try {
result = convertResult(callbackMethod.invoke(cb, callbackArgs));
}
catch (IllegalArgumentException | IllegalAccessException e) {
Native.getCallbackExceptionHandler().uncaughtException(cb, e);
}
catch (InvocationTargetException e) {
Native.getCallbackExceptionHandler().uncaughtException(cb, e.getTargetException());
}
}
// Synch any structure arguments back to native memory
for (int i=0;i < callbackArgs.length;i++) {
if (callbackArgs[i] instanceof Structure
&& !(callbackArgs[i] instanceof Structure.ByValue)) {
((Structure)callbackArgs[i]).autoWrite();
}
}
return result;
}
/** Called from native code. All arguments are in an array of
* Object as the first argument. Converts all arguments to types
* required by the actual callback method signature, and converts
* the result back into an appropriate native type.
* This method <em>must not</em> throw exceptions.
*/
@Override
public Object callback(Object[] args) {
try {
return invokeCallback(args);
}
catch (Throwable t) {
Native.getCallbackExceptionHandler().uncaughtException(getCallback(), t);
return null;
}
}
/** Convert argument from its basic native type to the given
* Java parameter type.
*/
private Object convertArgument(Object value, Class<?> dstType) {
if (value instanceof Pointer) {
if (dstType == String.class) {
value = ((Pointer)value).getString(0, encoding);
}
else if (dstType == WString.class) {
value = new WString(((Pointer)value).getWideString(0));
}
else if (dstType == String[].class) {
value = ((Pointer)value).getStringArray(0, encoding);
}
else if (dstType == WString[].class) {
value = ((Pointer)value).getWideStringArray(0);
}
else if (Callback.class.isAssignableFrom(dstType)) {
value = CallbackReference.getCallback(dstType, (Pointer)value);
}
else if (Structure.class.isAssignableFrom(dstType)) {
// If passed by value, don't hold onto the pointer, which
// is only valid for the duration of the callback call
if (Structure.ByValue.class.isAssignableFrom(dstType)) {
Structure s = Structure.newInstance((Class<? extends Structure>) dstType);
byte[] buf = new byte[s.size()];
((Pointer)value).read(0, buf, 0, buf.length);
s.getPointer().write(0, buf, 0, buf.length);
s.read();
value = s;
} else {
Structure s = Structure.newInstance((Class<? extends Structure>) dstType, (Pointer)value);
s.conditionalAutoRead();
value = s;
}
}
}
else if ((boolean.class == dstType || Boolean.class == dstType)
&& value instanceof Number) {
value = Function.valueOf(((Number)value).intValue() != 0);
}
return value;
}
private Object convertResult(Object value) {
if (toNative != null) {
value = toNative.toNative(value, new CallbackResultContext(callbackMethod));
}
if (value == null) {
return null;
}
Class<?> cls = value.getClass();
if (Structure.class.isAssignableFrom(cls)) {
if (Structure.ByValue.class.isAssignableFrom(cls)) {
return value;
}
return ((Structure)value).getPointer();
} else if (cls == boolean.class || cls == Boolean.class) {
return Boolean.TRUE.equals(value) ?
Function.INTEGER_TRUE : Function.INTEGER_FALSE;
} else if (cls == String.class || cls == WString.class) {
return getNativeString(value, cls == WString.class);
} else if (cls == String[].class || cls == WString[].class) {
StringArray sa = cls == String[].class
? new StringArray((String[])value, encoding)
: new StringArray((WString[])value);
// Delay GC until array itself is GC'd.
allocations.put(value, sa);
return sa;
} else if (Callback.class.isAssignableFrom(cls)) {
return getFunctionPointer((Callback)value);
}
return value;
}
@Override
public Class<?>[] getParameterTypes() {
return callbackMethod.getParameterTypes();
}
@Override
public Class<?> getReturnType() {
return callbackMethod.getReturnType();
}
}
/** Provide invocation handling for an auto-generated Java interface proxy
* for a native function pointer.
* Cf. Library.Handler
*/
private static class NativeFunctionHandler implements InvocationHandler {
private final Function function;
private final Map<String, ?> options;
public NativeFunctionHandler(Pointer address, int callingConvention, Map<String, ?> options) {
this.options = options;
this.function = new Function(address, callingConvention, (String) options.get(Library.OPTION_STRING_ENCODING));
}
/** Chain invocation to the native function. */
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Library.Handler.OBJECT_TOSTRING.equals(method)) {
String str = "Proxy interface to " + function;
Method m = (Method)options.get(Function.OPTION_INVOKING_METHOD);
Class<?> cls = findCallbackClass(m.getDeclaringClass());
str += " (" + cls.getName() + ")";
return str;
} else if (Library.Handler.OBJECT_HASHCODE.equals(method)) {
return Integer.valueOf(hashCode());
} else if (Library.Handler.OBJECT_EQUALS.equals(method)) {
Object o = args[0];
if (o != null && Proxy.isProxyClass(o.getClass())) {
return Function.valueOf(Proxy.getInvocationHandler(o) == this);
}
return Boolean.FALSE;
}
if (Function.isVarArgs(method)) {
args = Function.concatenateVarArgs(args);
}
return function.invoke(method.getReturnType(), args, options);
}
public Pointer getPointer() {
return function;
}
}
/** Returns whether the given class is supported in native code.
* Other types (String, WString, Structure, arrays, NativeMapped,
* etc) are supported in the Java library.
*/
private static boolean isAllowableNativeType(Class<?> cls) {
return cls == void.class || cls == Void.class
|| cls == boolean.class || cls == Boolean.class
|| cls == byte.class || cls == Byte.class
|| cls == short.class || cls == Short.class
|| cls == char.class || cls == Character.class
|| cls == int.class || cls == Integer.class
|| cls == long.class || cls == Long.class
|| cls == float.class || cls == Float.class
|| cls == double.class || cls == Double.class
|| (Structure.ByValue.class.isAssignableFrom(cls)
&& Structure.class.isAssignableFrom(cls))
|| Pointer.class.isAssignableFrom(cls);
}
private static Pointer getNativeString(Object value, boolean wide) {
if (value != null) {
NativeString ns = new NativeString(value.toString(), wide);
// Delay GC until string itself is GC'd.
allocations.put(value, ns);
return ns.getPointer();
}
return null;
}
private static final class CallbackReferenceDisposer implements Runnable {
private Pointer cbstruct;
public CallbackReferenceDisposer(Pointer cbstruct) {
this.cbstruct = cbstruct;
}
public synchronized void run() {
if (cbstruct != null) {
try {
Native.freeNativeCallback(cbstruct.peer);
} finally {
allocatedMemory.remove(cbstruct.peer);
cbstruct.peer = 0;
cbstruct = null;
}
}
}
}
}