Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
100644 191 lines (131 sloc) 12.679 kb
8b22412 @dblock The rest of the documentation.
dblock authored
1 Frequently Asked Questions
2 ==========================
6f9c712 @twall Add link to JNAerator.
4 I'm having trouble generating correct library mappings
5 ------------------------------------------------------
f7f4b34 @twall fix site doc link
6 Make sure you've read [this page]( and [this one]( Try [JNAerator]( If you find its output too verbose, delete the mappings you don't need, or copy out the ones you do need.
6f9c712 @twall Add link to JNAerator.
423984c @twall HOWTO extend platform mappings
8 JNA is missing function XXX in its platform library mappings
9 ------------------------------------------------------------
10 No, it's not, it's just waiting for you to add it :)
12 public interface MyUser32 extends User32 {
13 // DEFAULT_OPTIONS is critical for W32 API functions to simplify ASCII/UNICODE details
14 MyUser32 INSTANCE = (MyUser32)Native.loadLibrary("user32", W32APIOptions.DEFAULT_OPTIONS);
15 void ThatFunctionYouReallyNeed();
16 }
18 That's all it takes. If you'd like to submit the change back to JNA, make sure you provide a change log entry and corresponding test that invokes the function to prove that the mapping works. We don't really care what the API actually does, the call can be a very minimal invocation, but should ensure all the parameters are correctly passed and that you get a reasonable return value.
4f3dcfd @twall update docs
20 Calling `Native.loadLibrary()` causes an UnsatisfiedLinkError
21 -------------------------------------------------------------
23 Set the system property `jna.debug_load=true`, and JNA will print its library search steps to the console. `jna.debug_load.jna` will trace the search for JNA's own native support.
98c7993 @twall Bump `UnsatisfiedLinkError` help
25 My library mapping causes an UnsatisfiedLinkError
26 -------------------------------------------------
28 Use a dump utility to examine the names of your exported functions to make sure they match (nm on linux, [depends]( on Windows). On Windows, if the functions have a suffix of the form "@NN", you need to pass a `StdCallFunctionMapper` as an option when initializing your library interface. In general, you can use a function mapper (`FunctionMapper`) to change the name of the looked-up method, or an invocation mapper (`InvocationMapper`) for more extensive control over the method invocation.
2667202 @twall Move native long != Java long to top of list
30 How do I map a native `long` type?
31 ----------------------------------
176f3f3 @twall Update www/
33 Actually, no one ever asks this question, but they really need the answer. **Do not** use Java `long`!
2667202 @twall Move native long != Java long to top of list
35 On Windows, you can use a Java `int`, since the native long type is always 32 bits. On any other platform, the type may be 32 or 64 bits, so you should use the `NativeLong` type to ensure the proper size is used.
37 When should I use `Structure.ByReference`? `Structure.ByValue`? `Structure[]`?
38 ------------------------------------------------------------------------------
8b22412 @dblock The rest of the documentation.
dblock authored
40 Find your corresponding native declaration below:
42 typedef struct _simplestruct {
43 int myfield;
44 } simplestruct;
46 typedef struct _outerstruct {
47 simplestruct nested; // use Structure
48 } outerstruct;
50 typedef struct _outerstruct2 {
51 simplestruct *byref; // use Structure.ByReference
52 } outerstruct2;
54 typedef struct _outerstruct3 {
55 simplestruct array[4]; // use Structure[]
56 } outerstruct3;
58 typedef struct _outerstruct4 {
59 simplestruct* ptr_array[4]; // use Structure.ByReference[]
60 } outerstruct4;
62 // Field is a pointer to an array of struct
63 typedef struct _outerstruct5 {
64 simplestruct* ptr_to_array; // use Structure.ByReference, and use
8591ebd @twall Update www/
65 // Structure.toArray() to allocate the array,
66 // then assign the first array element to the field
8b22412 @dblock The rest of the documentation.
dblock authored
67 } outerstruct5;
69 // struct pointers as return value or argument
8591ebd @twall Update www/
70 simplestruct *myfunc(); // use Structure
96a4450 @twall Update www/
71 void myfunc(simplestruct* data); // use Structure
8591ebd @twall Update www/
72 void myfunc(simplestruct* data_array, int count); // use Structure[], and use Structure.toArray() to generate the array
73 void myfunc(simplestruct** data_array, int count); // use Structure.ByReference[]
8b22412 @dblock The rest of the documentation.
dblock authored
75 // struct (by value) as return value or argument
76 // use Structure.ByValue
77 simplestruct myfunc();
78 void myfunc(simplestruct);
80 If you need a `ByValue` or `ByReference` class, define them within your main `Structure` definition like this:
82 public class MyStructure extends Structure {
83 public static class ByValue extends MyStructure implements Structure.ByValue { }
84 public static class ByReference extends MyStructure implements Structure.ByReference { }
85 }
87 How do I read back a function's string result?
88 ----------------------------------------------
90 Suppose you have a function:
2667202 @twall Move native long != Java long to top of list
92 // Example A: Returns the number of characters written to the buffer
8b22412 @dblock The rest of the documentation.
dblock authored
93 int getString(char* buffer, int bufsize);
2667202 @twall Move native long != Java long to top of list
94 // Example B: Returns the number of characters written to the buffer
95 int getUnicodeString(wchar_t* buffer, int bufsize);
97 // Mapping A:
98 int getString(byte[] buf, int bufsize);
99 // Mapping B:
100 int getUnicodeString(char[] buf, int bufsize);
102 byte[] buf = new byte[256];
103 int len = getString(buf, buf.length);
104 String normalCString = Native.toString(buf);
105 String embeddedNULs = new String(buf, 0, len);
8b22412 @dblock The rest of the documentation.
dblock authored
107 The native code is expecting a fixed-size buffer, which it will fill in with the requested data. A Java `String` is not appropriate here, since Strings are immutable. Nor is a Java `StringBuffer`, since the native code only fills the buffer and does not change its size. The appropriate argument type would be either `byte[]`, `Memory`, or an NIO Buffer, with the size of the object passed as the second argument. The method `Native.toString(byte[])` may then be used to convert the array of byte into a Java String.
2667202 @twall Move native long != Java long to top of list
109 // Example A: Returns a C string directly
110 const char* getString();
111 // Example B: Returns a wide character C string directly
112 const wchar_t* getString();
114 If the string is returned directly, your Java mapping can use the `String` or `WString` type as a return value (as appropriate).
115 Note that if the native code allocates memory for the string, you should return `Pointer` instead so that you can free the memory
116 at some later point.
118 // Mapping A
119 String getString();
120 // Mapping B
121 WString getString();
122 // Mapping C, if native code allocates memory
123 // Use Pointer.getString(0) to extract the String data,
124 // then call the recommended native method with the Pointer
125 // value to free the memory
126 Pointer getString();
8b22412 @dblock The rest of the documentation.
dblock authored
128 My library sometimes causes a VM crash
129 --------------------------------------
131 Double check the signature of the method causing the crash to ensure all arguments are of the appropriate size and type. Be especially careful with native pointer variations. See also information on debugging structure definitions.
133 My Windows library mapping causes a VM crash on every call
134 ----------------------------------------------------------
136 If your library uses the stdcall calling convention, your interface should extend the `StdCallLibrary` interface. Using the wrong calling convention for a library will usually cause a VM crash.
138 How do I get an arbitrary Pointer value?
139 ----------------------------------------
141 First, you probably don't actually want an arbitrary value. Ask yourself what you're really trying to do. Remember, type safety is your friend.
143 `Pointer.createConstant()` should be used when you need a special value that is not really a pointer (`NULL` usually serves this purpose, but some C programmers like to check pointers for special integer values instead). The `Pointer` produced by this function can't actually be used to access memory. `Pointer.share()` can be used to generate a new `Pointer` as an offset from an existing one. `java.nio.Buffer` can be used to wrap a Java array with a different offset and length than the original.
145 Clean up the sloppy C code by declaring an appropriate function interface. If your function in C takes either a `Pointer` or an integer type, simply declare both method signatures in your JNA interface. They will both invoke the same function, but you get the added benefit of type checking on the arguments.
b95bcb2 @twall Note existence of Pointer(long) ctor
147 If you really, really, *have* to convert an integer value into a `Pointer`, use the `Pointer(long)` constructor.
8b22412 @dblock The rest of the documentation.
dblock authored
150 Debugging Structure Definitions
151 -------------------------------
153 Normally when you invoke `toString` on a `Structure`, it will print each defined field with its calculated memory offset. If when launching the VM, you pass it `"-Djna.dump_memory=true"`, `toString` will also dump the contents of the corresponding native memory. This is useful to determine if you've added or omitted a field, or chosen an incorrect size. Viewing the memory as bytes usually makes it clear where field boundaries should be, assuming the memory has been initialized by native code.
489d797 @twall update note on winCE
155 Does JNA work with J2ME/Windows CE/Mobile?
156 ------------------------------------------
8b22412 @dblock The rest of the documentation.
dblock authored
489d797 @twall update note on winCE
158 There is an implementation included in the regular JNA distribution built with cegcc and tested against phoneME.
8b22412 @dblock The rest of the documentation.
dblock authored
160 I need to use a COM/OCX/ActiveX object. Can JNA do that?
161 --------------------------------------------------------
b95bcb2 @twall Note existence of Pointer(long) ctor
163 Not really. Try JACOB or com4j, both of which can parse a COM interface definition and generate a Java object to match it. JNAerator is also working on generating COM bindings.
8b22412 @dblock The rest of the documentation.
dblock authored
165 Why does the VM sometimes crash in my shutdown hook on Windows?
166 ---------------------------------------------------------------
168 If you are using direct mapping, make sure you keep a reference to the JNA class `com.sun.jna.Native` until your shutdown hook completes. If you are using interface mapping, your library proxy will be keeping a reference internally, so an explicit reference is not required.
170 If JNA unpacks its native code from its own jar file, it saves it in a temporary location and attempts to remove it when the `Native` class is finalized (which may or may not happen as the VM exits). In order to do so, it must first unload its native library from memory.
172 Alternatively, if the `jnidispatch.dll` native library is found in the system library load path, JNA will not attempt to unload it, although your shutdown hook must still ensure that the JNA classes you wish to use have not been GC'd.
174 I get an UnsatisfiedLinkError on OSX when I provide my native library via Java Web Start
175 ----------------------------------------------------------------------------------------
177 Libraries loaded via the JNLP class loader on OSX must be named with a .jnilib suffix. The class loader won't find resources included with the `nativelib` tag if they have a .dylib suffix.
179 How does JNA performance compare to custom JNI?
180 -----------------------------------------------
182 JNA direct mapping can provide performance near that of custom JNI. Nearly all the type mapping features of interface mapping are available, although automatic type conversion will likely incur some overhead.
184 The calling overhead for a single native call using JNA interface mapping can be an order of magnitude (~10X) greater time than equivalent custom JNI (whether it actually does in the context of your application is a different question). In raw terms, the calling overhead is on the order of hundreds of microseconds instead of tens of microseconds. Note that that's the call overhead, not the total call time. This magnitude is typical of the difference between systems using dynamically-maintained type information and systems where type information is statically compiled. JNI hard-codes type information in the method invocation, where JNA interface mapping dynamically determines type information at runtime.
186 You might expect a speedup of about an order of magnitude moving to JNA direct mapping, and a factor of two or three moving from there to custom JNI. The actual difference will vary depending on usage and function signatures. As with any optimization process, you should determine first where you need a speed increase, and then see how much difference there is by performing targeted optimizations. The ease of programming everything in Java usually outweighs small performance gains when using custom JNI.
22cb28e @wolftobias Update
wolftobias authored
188 JNA COM support
189 ---------------
190 There is a new implementation to support COM in conjunction with JNA directly. The development is relatively young, honestly the development has been finished just end of February '13. Please note that fact if you use the COM support in JNA, there could be things missing or not absolutely tested or still not working. Please use the jna user group to report your experience with the JNA Com support.
Something went wrong with that request. Please try again.