-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Function.java
843 lines (793 loc) · 35.4 KB
/
Function.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
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
/*
* 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 java.lang.reflect.Method;
import java.util.Collections;
import java.util.Map;
/**
* <p>An abstraction for a native function pointer. An instance of
* <code>Function</code> represents a pointer to some native function.
* {@link #invoke(Class,Object[],Map)} is the primary means to call
* the function. </p>
* <a name=callflags></a>
* Function call behavior may be modified by passing one of the following call
* flags:
* <ul>
* <li>{@link Function#C_CONVENTION} Use C calling convention (default)
* <li>{@link Function#ALT_CONVENTION} Use alternate calling convention (e.g. stdcall)
* <li>{@link Function#THROW_LAST_ERROR} Throw a {@link LastErrorException} if
* the native function sets the system error to a non-zero value (errno or
* GetLastError). Setting this flag will cause the system error to be cleared
* prior to native function invocation.
* </ul>
*
* @author Sheng Liang, originator
* @author Todd Fast, suitability modifications
* @author Timothy Wall
* @see Pointer
*/
public class Function extends Pointer {
/** Any argument which implements this interface will have the
* {@link #read} method called immediately after function invocation.
*/
public interface PostCallRead {
/** Perform any necessary post-call synchronization. Normally this
* just means reading from native memory any changes made by
* the native function call.
*/
void read();
}
/** Maximum number of arguments supported by a JNA function call. */
@java.lang.annotation.Native
public static final int MAX_NARGS = 256;
/** Standard C calling convention. */
@java.lang.annotation.Native
public static final int C_CONVENTION = 0;
/** First alternate convention (currently used only for w32 stdcall). */
@java.lang.annotation.Native
public static final int ALT_CONVENTION = 0x3F;
@java.lang.annotation.Native
private static final int MASK_CC = 0x3F;
/** Whether to throw an exception if last error is non-zero after call. */
@java.lang.annotation.Native
public static final int THROW_LAST_ERROR = 0x40;
/** Mask for number of fixed args (max 255) for varargs calls. */
@java.lang.annotation.Native
public static final int USE_VARARGS = 0xFF;
/** Offset of USE_VARARGS in call flags */
@java.lang.annotation.Native
private static final int USE_VARARGS_SHIFT = 7;
static final Integer INTEGER_TRUE = Integer.valueOf(-1);
static final Integer INTEGER_FALSE = Integer.valueOf(0);
/**
* Obtain a <code>Function</code> representing a native
* function that follows the standard "C" calling convention.
*
* <p>The allocated instance represents a pointer to the named native
* function from the named library, called with the standard "C" calling
* convention.
*
* @param libraryName
* Library in which to find the native function
* @param functionName
* Name of the native function to be linked with
* @throws UnsatisfiedLinkError if the library is not found or
* the given function name is not found within the library.
*/
public static Function getFunction(String libraryName, String functionName) {
return NativeLibrary.getInstance(libraryName).getFunction(functionName);
}
/**
* Obtain a <code>Function</code> representing a native
* function.
*
* <p>The allocated instance represents a pointer to the named native
* function from the named library.
*
* @param libraryName
* Library in which to find the function
* @param functionName
* Name of the native function to be linked with
* @param callFlags
* Function <a href="#callflags">call flags</a>
*
* @throws UnsatisfiedLinkError if the library is not found or
* the given function name is not found within the library.
*/
public static Function getFunction(String libraryName, String functionName, int callFlags) {
return NativeLibrary.getInstance(libraryName).getFunction(functionName, callFlags, null);
}
/**
* Obtain a <code>Function</code> representing a native
* function.
*
* <p>The allocated instance represents a pointer to the named native
* function from the named library.
*
* @param libraryName
* Library in which to find the function
* @param functionName
* Name of the native function to be linked with
* @param callFlags
* Function <a href="#callflags">call flags</a>
* @param encoding
* Encoding to use for conversion between Java and native
* strings.
*
* @throws UnsatisfiedLinkError if the library is not found or
* the given function name is not found within the library.
*/
public static Function getFunction(String libraryName, String functionName, int callFlags, String encoding) {
return NativeLibrary.getInstance(libraryName).getFunction(functionName, callFlags, encoding);
}
/**
* Obtain a <code>Function</code> representing a native
* function pointer. In general, this function should be used by dynamic
* languages; Java code should allow JNA to bind to a specific Callback
* interface instead by defining a return type or Structure field type.
*
* <p>The allocated instance represents a pointer to the native
* function pointer.
*
* @param p Native function pointer
*/
public static Function getFunction(Pointer p) {
return getFunction(p, 0, null);
}
/**
* Obtain a <code>Function</code> representing a native
* function pointer. In general, this function should be used by dynamic
* languages; Java code should allow JNA to bind to a specific Callback
* interface instead by defining a return type or Structure field type.
*
* <p>The allocated instance represents a pointer to the native
* function pointer.
*
* @param p
* Native function pointer
* @param callFlags
* Function <a href="#callflags">call flags</a>
*/
public static Function getFunction(Pointer p, int callFlags) {
return getFunction(p, callFlags, null);
}
/**
* Obtain a <code>Function</code> representing a native
* function pointer. In general, this function should be used by dynamic
* languages; Java code should allow JNA to bind to a specific Callback
* interface instead by defining a return type or Structure field type.
*
* <p>The allocated instance represents a pointer to the native
* function pointer.
*
* @param p
* Native function pointer
* @param callFlags
* Function <a href="#callflags">call flags</a>
* @param encoding
* Encoding to use for conversion between Java and native
* strings.
*/
public static Function getFunction(Pointer p, int callFlags, String encoding) {
return new Function(p, callFlags, encoding);
}
// Keep a reference to the NativeLibrary so it does not get garbage
// collected until the function is
private NativeLibrary library;
private final String functionName;
final String encoding;
final int callFlags;
final Map<String, ?> options;
/** For internal JNA use. */
static final String OPTION_INVOKING_METHOD = "invoking-method";
/** For checking if methods declare varargs */
private static final VarArgsChecker IS_VARARGS = VarArgsChecker.create();
/**
* Create a new <code>Function</code> that is linked with a native
* function that follows the given calling convention.
*
* <p>The allocated instance represents a pointer to the named native
* function from the supplied library, called with the given calling
* convention.
*
* @param library
* {@link NativeLibrary} in which to find the function
* @param functionName
* Name of the native function to be linked with
* @param callFlags
* Function <a href="#callflags">call flags</a>
* @param encoding
* Encoding for conversion between Java and native strings.
* @throws UnsatisfiedLinkError if the given function name is
* not found within the library.
*/
Function(NativeLibrary library, String functionName, int callFlags, String encoding) {
checkCallingConvention(callFlags & MASK_CC);
if (functionName == null) {
throw new NullPointerException("Function name must not be null");
}
this.library = library;
this.functionName = functionName;
this.callFlags = callFlags;
this.options = library.getOptions();
this.encoding = encoding != null ? encoding : Native.getDefaultStringEncoding();
try {
this.peer = library.getSymbolAddress(functionName);
} catch(UnsatisfiedLinkError e) {
throw new UnsatisfiedLinkError("Error looking up function '"
+ functionName + "': "
+ e.getMessage());
}
}
/**
* Create a new <code>Function</code> that is linked with a native
* function that follows the given calling convention.
*
* <p>The allocated instance represents a pointer to the given
* function address, called with the given calling
* convention.
*
* @param functionAddress
* Address of the native function
* @param callFlags
* Function <a href="#callflags">call flags</a>
* @param encoding
* Encoding for conversion between Java and native strings.
*/
Function(Pointer functionAddress, int callFlags, String encoding) {
checkCallingConvention(callFlags & MASK_CC);
if (functionAddress == null
|| functionAddress.peer == 0) {
throw new NullPointerException("Function address may not be null");
}
this.functionName = functionAddress.toString();
this.callFlags = callFlags;
this.peer = functionAddress.peer;
this.options = Collections.EMPTY_MAP;
this.encoding = encoding != null
? encoding : Native.getDefaultStringEncoding();
}
private void checkCallingConvention(int convention)
throws IllegalArgumentException {
// TODO: perform per-platform calling convention checks
if ((convention & MASK_CC) != convention) {
throw new IllegalArgumentException("Unrecognized calling convention: "
+ convention);
}
}
public String getName() {
return functionName;
}
public int getCallingConvention() {
return callFlags & MASK_CC;
}
/** Invoke the native function with the given arguments, returning the
* native result as an Object.
*/
public Object invoke(Class<?> returnType, Object[] inArgs) {
return invoke(returnType, inArgs, this.options);
}
/** Invoke the native function with the given arguments, returning the
* native result as an Object.
*/
public Object invoke(Class<?> returnType, Object[] inArgs, Map<String, ?> options) {
Method invokingMethod = (Method)options.get(OPTION_INVOKING_METHOD);
Class<?>[] paramTypes = invokingMethod != null ? invokingMethod.getParameterTypes() : null;
return invoke(invokingMethod, paramTypes, returnType, inArgs, options);
}
/** Invoke the native function with the given arguments, returning the
* native result as an Object. This method can be called if invoking method and parameter
* types are already at hand. When calling {@link Function#invoke(Class, Object[], Map)},
* the method has to be in the options under key {@link Function#OPTION_INVOKING_METHOD}.
*/
Object invoke(Method invokingMethod, Class<?>[] paramTypes, Class<?> returnType, Object[] inArgs, Map<String, ?> options) {
// Clone the argument array to obtain a scratch space for modified
// types/values
Object[] args = { };
if (inArgs != null) {
if (inArgs.length > MAX_NARGS) {
throw new UnsupportedOperationException("Maximum argument count is " + MAX_NARGS);
}
args = new Object[inArgs.length];
System.arraycopy(inArgs, 0, args, 0, args.length);
}
TypeMapper mapper = (TypeMapper)options.get(Library.OPTION_TYPE_MAPPER);
boolean allowObjects = Boolean.TRUE.equals(options.get(Library.OPTION_ALLOW_OBJECTS));
boolean isVarArgs = args.length > 0 && invokingMethod != null ? isVarArgs(invokingMethod) : false;
int fixedArgs = args.length > 0 && invokingMethod != null ? fixedArgs(invokingMethod) : 0;
for (int i=0; i < args.length; i++) {
Class<?> paramType = invokingMethod != null
? (isVarArgs && i >= paramTypes.length-1
? paramTypes[paramTypes.length-1].getComponentType()
: paramTypes[i])
: null;
args[i] = convertArgument(args, i, invokingMethod, mapper, allowObjects, paramType);
}
Class<?> nativeReturnType = returnType;
FromNativeConverter resultConverter = null;
if (NativeMapped.class.isAssignableFrom(returnType)) {
NativeMappedConverter tc = NativeMappedConverter.getInstance(returnType);
resultConverter = tc;
nativeReturnType = tc.nativeType();
} else if (mapper != null) {
resultConverter = mapper.getFromNativeConverter(returnType);
if (resultConverter != null) {
nativeReturnType = resultConverter.nativeType();
}
}
Object result = invoke(args, nativeReturnType, allowObjects, fixedArgs);
// Convert the result to a custom value/type if appropriate
if (resultConverter != null) {
FromNativeContext context;
if (invokingMethod != null) {
context = new MethodResultContext(returnType, this, inArgs, invokingMethod);
} else {
context = new FunctionResultContext(returnType, this, inArgs);
}
result = resultConverter.fromNative(result, context);
}
// Sync all memory which might have been modified by the native call
if (inArgs != null) {
for (int i=0; i < inArgs.length; i++) {
Object inArg = inArgs[i];
if (inArg == null)
continue;
if (inArg instanceof Structure) {
if (!(inArg instanceof Structure.ByValue)) {
((Structure)inArg).autoRead();
}
} else if (args[i] instanceof PostCallRead) {
((PostCallRead)args[i]).read();
if (args[i] instanceof PointerArray) {
PointerArray array = (PointerArray)args[i];
if (Structure.ByReference[].class.isAssignableFrom(inArg.getClass())) {
Class<? extends Structure> type = (Class<? extends Structure>) inArg.getClass().getComponentType();
Structure[] ss = (Structure[])inArg;
for (int si=0;si < ss.length;si++) {
Pointer p = array.getPointer(Native.POINTER_SIZE * si);
ss[si] = Structure.updateStructureByReference((Class<Structure>)type, ss[si], p);
}
}
}
} else if (Structure[].class.isAssignableFrom(inArg.getClass())) {
Structure.autoRead((Structure[])inArg);
}
}
}
return result;
}
/* @see NativeLibrary#NativeLibrary(String,String,long,Map) implementation */
Object invoke(Object[] args, Class<?> returnType, boolean allowObjects) {
return invoke(args, returnType, allowObjects, 0);
}
/* @see NativeLibrary#NativeLibrary(String,String,long,Map) implementation */
Object invoke(Object[] args, Class<?> returnType, boolean allowObjects, int fixedArgs) {
Object result = null;
int callFlags = this.callFlags | ((fixedArgs & USE_VARARGS) << USE_VARARGS_SHIFT);
if (returnType == null || returnType==void.class || returnType==Void.class) {
Native.invokeVoid(this, this.peer, callFlags, args);
result = null;
} else if (returnType==boolean.class || returnType==Boolean.class) {
result = valueOf(Native.invokeInt(this, this.peer, callFlags, args) != 0);
} else if (returnType==byte.class || returnType==Byte.class) {
result = Byte.valueOf((byte)Native.invokeInt(this, this.peer, callFlags, args));
} else if (returnType==short.class || returnType==Short.class) {
result = Short.valueOf((short)Native.invokeInt(this, this.peer, callFlags, args));
} else if (returnType==char.class || returnType==Character.class) {
result = Character.valueOf((char)Native.invokeInt(this, this.peer, callFlags, args));
} else if (returnType==int.class || returnType==Integer.class) {
result = Integer.valueOf(Native.invokeInt(this, this.peer, callFlags, args));
} else if (returnType==long.class || returnType==Long.class) {
result = Long.valueOf(Native.invokeLong(this, this.peer, callFlags, args));
} else if (returnType==float.class || returnType==Float.class) {
result = Float.valueOf(Native.invokeFloat(this, this.peer, callFlags, args));
} else if (returnType==double.class || returnType==Double.class) {
result = Double.valueOf(Native.invokeDouble(this, this.peer, callFlags, args));
} else if (returnType==String.class) {
result = invokeString(callFlags, args, false);
} else if (returnType==WString.class) {
String s = invokeString(callFlags, args, true);
if (s != null) {
result = new WString(s);
}
} else if (Pointer.class.isAssignableFrom(returnType)) {
return invokePointer(callFlags, args);
} else if (Structure.class.isAssignableFrom(returnType)) {
if (Structure.ByValue.class.isAssignableFrom(returnType)) {
Structure s =
Native.invokeStructure(this, this.peer, callFlags, args,
Structure.newInstance((Class<? extends Structure>)returnType));
s.autoRead();
result = s;
} else {
result = invokePointer(callFlags, args);
if (result != null) {
Structure s = Structure.newInstance((Class<? extends Structure>)returnType, (Pointer)result);
s.conditionalAutoRead();
result = s;
}
}
} else if (Callback.class.isAssignableFrom(returnType)) {
result = invokePointer(callFlags, args);
if (result != null) {
result = CallbackReference.getCallback(returnType, (Pointer)result);
}
} else if (returnType==String[].class) {
Pointer p = invokePointer(callFlags, args);
if (p != null) {
result = p.getStringArray(0, encoding);
}
} else if (returnType==WString[].class) {
Pointer p = invokePointer(callFlags, args);
if (p != null) {
String[] arr = p.getWideStringArray(0);
WString[] warr = new WString[arr.length];
for (int i=0;i < arr.length;i++) {
warr[i] = new WString(arr[i]);
}
result = warr;
}
} else if (returnType==Pointer[].class) {
Pointer p = invokePointer(callFlags, args);
if (p != null) {
result = p.getPointerArray(0);
}
} else if (allowObjects) {
result = Native.invokeObject(this, this.peer, callFlags, args);
if (result != null
&& !returnType.isAssignableFrom(result.getClass())) {
throw new ClassCastException("Return type " + returnType
+ " does not match result "
+ result.getClass());
}
} else {
throw new IllegalArgumentException("Unsupported return type " + returnType + " in function " + getName());
}
return result;
}
private Pointer invokePointer(int callFlags, Object[] args) {
long ptr = Native.invokePointer(this, this.peer, callFlags, args);
return ptr == 0 ? null : new Pointer(ptr);
}
private Object convertArgument(Object[] args, int index,
Method invokingMethod, TypeMapper mapper,
boolean allowObjects, Class<?> expectedType) {
Object arg = args[index];
if (arg != null) {
Class<?> type = arg.getClass();
ToNativeConverter converter = null;
if (NativeMapped.class.isAssignableFrom(type)) {
converter = NativeMappedConverter.getInstance(type);
} else if (mapper != null) {
converter = mapper.getToNativeConverter(type);
}
if (converter != null) {
ToNativeContext context;
if (invokingMethod != null) {
context = new MethodParameterContext(this, args, index, invokingMethod) ;
}
else {
context = new FunctionParameterContext(this, args, index);
}
arg = converter.toNative(arg, context);
}
}
if (arg == null || isPrimitiveArray(arg.getClass())) {
return arg;
}
Class<?> argClass = arg.getClass();
// Convert Structures to native pointers
if (arg instanceof Structure) {
Structure struct = (Structure)arg;
struct.autoWrite();
if (struct instanceof Structure.ByValue) {
// Double-check against the method signature, if available
Class<?> ptype = struct.getClass();
if (invokingMethod != null) {
Class<?>[] ptypes = invokingMethod.getParameterTypes();
if (IS_VARARGS.isVarArgs(invokingMethod)) {
if (index < ptypes.length-1) {
ptype = ptypes[index];
} else {
Class<?> etype = ptypes[ptypes.length-1].getComponentType();
if (etype != Object.class) {
ptype = etype;
}
}
} else {
ptype = ptypes[index];
}
}
if (Structure.ByValue.class.isAssignableFrom(ptype)) {
return struct;
}
}
return struct.getPointer();
} else if (arg instanceof Callback) {
// Convert Callback to Pointer
return CallbackReference.getFunctionPointer((Callback)arg);
} else if (arg instanceof String) {
// String arguments are converted to native pointers here rather
// than in native code so that the values will be valid until
// this method returns.
// Convert String to native pointer (const)
return new NativeString((String)arg, encoding).getPointer();
} else if (arg instanceof WString) {
// Convert WString to native pointer (const)
return new NativeString(arg.toString(), true).getPointer();
} else if (arg instanceof Boolean) {
// Default conversion of boolean to int; if you want something
// different, use a ToNativeConverter
return Boolean.TRUE.equals(arg) ? INTEGER_TRUE : INTEGER_FALSE;
} else if (String[].class == argClass) {
return new StringArray((String[])arg, encoding);
} else if (WString[].class == argClass) {
return new StringArray((WString[])arg);
} else if (Pointer[].class == argClass) {
return new PointerArray((Pointer[])arg);
} else if (NativeMapped[].class.isAssignableFrom(argClass)) {
return new NativeMappedArray((NativeMapped[])arg);
} else if (Structure[].class.isAssignableFrom(argClass)) {
// If the signature is Structure[], disallow
// Structure.ByReference[] and Structure.ByReference elements
Structure[] ss = (Structure[])arg;
Class<?> type = argClass.getComponentType();
boolean byRef = Structure.ByReference.class.isAssignableFrom(type);
if (expectedType != null) {
if (!Structure.ByReference[].class.isAssignableFrom(expectedType)) {
if (byRef) {
throw new IllegalArgumentException("Function " + getName()
+ " declared Structure[] at parameter "
+ index + " but array of "
+ type + " was passed");
}
for (int i=0;i < ss.length;i++) {
if (ss[i] instanceof Structure.ByReference) {
throw new IllegalArgumentException("Function " + getName()
+ " declared Structure[] at parameter "
+ index + " but element " + i
+ " is of Structure.ByReference type");
}
}
}
}
if (byRef) {
Structure.autoWrite(ss);
Pointer[] pointers = new Pointer[ss.length + 1];
for (int i=0;i < ss.length;i++) {
pointers[i] = ss[i] != null ? ss[i].getPointer() : null;
}
return new PointerArray(pointers);
} else if (ss.length == 0) {
throw new IllegalArgumentException("Structure array must have non-zero length");
} else if (ss[0] == null) {
Structure.newInstance((Class<? extends Structure>) type).toArray(ss);
return ss[0].getPointer();
} else {
Structure.autoWrite(ss);
return ss[0].getPointer();
}
} else if (argClass.isArray()){
throw new IllegalArgumentException("Unsupported array argument type: "
+ argClass.getComponentType());
} else if (allowObjects) {
return arg;
} else if (!Native.isSupportedNativeType(arg.getClass())) {
throw new IllegalArgumentException("Unsupported argument type "
+ arg.getClass().getName()
+ " at parameter " + index
+ " of function " + getName());
}
return arg;
}
private boolean isPrimitiveArray(Class<?> argClass) {
return argClass.isArray()
&& argClass.getComponentType().isPrimitive();
}
/**
* Call the native function being represented by this object
*
* @param args Arguments to pass to the native function
*/
public void invoke(Object[] args) {
invoke(Void.class, args);
}
/**
* Call the native function being represented by this object
*
* @param callFlags calling convention to be used
* @param args Arguments to pass to the native function
* @param wide whether the native string uses <code>wchar_t</code>; if
* false, <code>char</code> is assumed
*
* @return The value returned by the target native function, as a String
*/
private String invokeString(int callFlags, Object[] args, boolean wide) {
Pointer ptr = invokePointer(callFlags, args);
String s = null;
if (ptr != null) {
if (wide) {
s = ptr.getWideString(0);
}
else {
s = ptr.getString(0, encoding);
}
}
return s;
}
/** Provide a human-readable representation of this object. */
@Override
public String toString() {
if (library != null) {
return "native function " + functionName + "(" + library.getName()
+ ")@0x" + Long.toHexString(peer);
}
return "native function@0x" + Long.toHexString(peer);
}
/** Convenience method for
* {@link #invoke(Class,Object[]) invokeObject(Object.class, args)}.
*/
public Object invokeObject(Object[] args) {
return invoke(Object.class, args);
}
/** Convenience method for
* {@link #invoke(Class,Object[]) invoke(Pointer.class, args)}.
*/
public Pointer invokePointer(Object[] args) {
return (Pointer)invoke(Pointer.class, args);
}
/** Convenience method for
* {@link #invoke(Class,Object[]) invoke(String.class, args)}
* or {@link #invoke(Class,Object[]) invoke(WString.class, args)}
* @param args Arguments passed to native function
* @param wide Whether the return value is of type <code>wchar_t*</code>;
* if false, the return value is of type <code>char*</code>.
*/
public String invokeString(Object[] args, boolean wide) {
Object o = invoke(wide ? WString.class : String.class, args);
return o != null ? o.toString() : null;
}
/** Convenience method for
* {@link #invoke(Class,Object[]) invoke(Integer.class, args)}.
*/
public int invokeInt(Object[] args) {
return ((Integer)invoke(Integer.class, args)).intValue();
}
/** Convenience method for
* {@link #invoke(Class,Object[]) invoke(Long.class, args)}.
*/
public long invokeLong(Object[] args) {
return ((Long)invoke(Long.class, args)).longValue();
}
/** Convenience method for
* {@link #invoke(Class,Object[]) invoke(Float.class, args)}.
*/
public float invokeFloat(Object[] args) {
return ((Float)invoke(Float.class, args)).floatValue();
}
/** Convenience method for
* {@link #invoke(Class,Object[]) invoke(Double.class, args)}.
*/
public double invokeDouble(Object[] args) {
return ((Double)invoke(Double.class, args)).doubleValue();
}
/** Convenience method for
* {@link #invoke(Class,Object[]) invoke(Void.class, args)}.
*/
public void invokeVoid(Object[] args) {
invoke(Void.class, args);
}
/** Two function pointers are equal if they share the same peer address
* and calling convention.
*/
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (o == null) return false;
if (o.getClass() == getClass()) {
Function other = (Function)o;
return other.callFlags == this.callFlags
&& other.options.equals(this.options)
&& other.peer == this.peer;
}
return false;
}
/** Provide a unique hash code for {@link Function}s which are
equivalent.
*/
@Override
public int hashCode() {
return callFlags + options.hashCode() + super.hashCode();
}
/** Concatenate varargs with normal args to obtain a simple argument
* array.
*/
static Object[] concatenateVarArgs(Object[] inArgs) {
// If the final argument is an array of something other than
// primitives, Structure, or String, treat it as varargs and
// concatenate the previous arguments with the varargs elements.
if (inArgs != null && inArgs.length > 0) {
Object lastArg = inArgs[inArgs.length-1];
Class<?> argType = lastArg != null ? lastArg.getClass() : null;
if (argType != null && argType.isArray()) {
Object[] varArgs = (Object[])lastArg;
// Promote float varargs to double (https://github.com/java-native-access/jna/issues/463).
for (int i=0; i < varArgs.length; i++) {
if (varArgs[i] instanceof Float) {
varArgs[i] = (double)(Float)varArgs[i];
}
}
Object[] fullArgs = new Object[inArgs.length+varArgs.length];
System.arraycopy(inArgs, 0, fullArgs, 0, inArgs.length-1);
System.arraycopy(varArgs, 0, fullArgs, inArgs.length-1, varArgs.length);
// For convenience, always append a NULL argument to the end
// of varargs, whether the called API requires it or not. If
// it is not needed, it will be ignored, but if it *is*
// required, it avoids forcing the Java client to always
// explicitly add it.
fullArgs[fullArgs.length-1] = null;
inArgs = fullArgs;
}
}
return inArgs;
}
/** Varargs are only supported on 1.5+. */
static boolean isVarArgs(Method m) {
return IS_VARARGS.isVarArgs(m);
}
/** Varargs are only supported on 1.5+. */
static int fixedArgs(Method m) {
return IS_VARARGS.fixedArgs(m);
}
private static class NativeMappedArray extends Memory implements PostCallRead {
private final NativeMapped[] original;
public NativeMappedArray(NativeMapped[] arg) {
super(Native.getNativeSize(arg.getClass(), arg));
this.original = arg;
setValue(0, original, original.getClass());
}
@Override
public void read() {
getValue(0, original.getClass(), original);
}
}
private static class PointerArray extends Memory implements PostCallRead {
private final Pointer[] original;
public PointerArray(Pointer[] arg) {
super(Native.POINTER_SIZE * (arg.length+1));
this.original = arg;
for (int i=0;i < arg.length;i++) {
setPointer(i*Native.POINTER_SIZE, arg[i]);
}
setPointer(Native.POINTER_SIZE*arg.length, null);
}
@Override
public void read() {
read(0, original, 0, original.length);
}
}
/** Implementation of Boolean.valueOf for older VMs. */
static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}
}