Permalink
Browse files

The rest of the documentation.

1 parent 92d721d commit 8b22412e55c1412ea1684ddbf76101e1d7af0ad7 @dblock dblock committed May 23, 2011
View
130 CHANGES
@@ -4,25 +4,25 @@ Release 3.x.x
Features
--------
-* Facilitate `Memory</code> subclasses (jbellis).
+* Facilitate `Memory` subclasses (jbellis).
* Allow multiple fields of the same type in Unions (Francis Barber).
-* Add `platform.win32.Advapi32.AdjustTokenPrivileges</code>, `platform.win32.Advapi32.LookupPrivilegeName</code>, `platform.win32.Advapi32.LookupPrivilegeValue</code>, `platform.win32.Advapi32.ImpersonateSelf</code>.
-* Add `platform.win32.Advapi32.DuplicateTokenEx</code>, `platform.win32.Advapi32.CreateProcessAsUser</code>, `platform.win32.Kernel32.GetExitCodeProcess</code>, `platform.win32.Kernel32.TerminateProcess</code>, `platform.win32.Kernel32.ReadFile</code>, `platform.win32.Kernel32.CreatePipe</code>, `platform.win32.Kernel32.SetHandleInformation</code> and related constants / structures in `platform.win32.WinBase</code> and `platform.win32.WinNT</code>. Please note that the `SECURITY_ATTRIBUTES</code> structure has been moved from `platform.win32.WinNT</code> to `platform.win32.WinBase</code>.
-* Add `platform.win32.Kernel32.DeleteFile</code> and `platform.win32.Kernel32Util.deleteFile</code>.
-* Add `platform.win32.Kernel32.GetFileAttributes</code> and `platform.win32.Kernel32Util.getFileAttributes</code>.
-* Add `platform.win32.Kernel32.GetTickCount</code>.
-* Add Win32 Service functions to `platform.win32.Advapi32</code>.
-* Add `platform.win32.W32ServiceManager</code> and `W32Service</code>.
-* Add Win32 Event Logging functions to `platform.win32.Advapi32</code> and `platform.win32.Advapi32Util.EventLogIterator</code>.
-* `platform.win32.Advapi32Util.registryCreateKey</code> returns `true</code> if key was created, `false</code> if it already exists.
-* Add `REG_BINARY</code>, `REG_EXPAND_SZ</code> and `REG_MULTI_SZ</code> support to `platform.win32.Advapi32Util</code> registry functions.
+* Add `platform.win32.Advapi32.AdjustTokenPrivileges`, `platform.win32.Advapi32.LookupPrivilegeName`, `platform.win32.Advapi32.LookupPrivilegeValue`, `platform.win32.Advapi32.ImpersonateSelf`.
+* Add `platform.win32.Advapi32.DuplicateTokenEx`, `platform.win32.Advapi32.CreateProcessAsUser`, `platform.win32.Kernel32.GetExitCodeProcess`, `platform.win32.Kernel32.TerminateProcess`, `platform.win32.Kernel32.ReadFile`, `platform.win32.Kernel32.CreatePipe`, `platform.win32.Kernel32.SetHandleInformation` and related constants / structures in `platform.win32.WinBase` and `platform.win32.WinNT`. Please note that the `SECURITY_ATTRIBUTES` structure has been moved from `platform.win32.WinNT` to `platform.win32.WinBase`.
+* Add `platform.win32.Kernel32.DeleteFile` and `platform.win32.Kernel32Util.deleteFile`.
+* Add `platform.win32.Kernel32.GetFileAttributes` and `platform.win32.Kernel32Util.getFileAttributes`.
+* Add `platform.win32.Kernel32.GetTickCount`.
+* Add Win32 Service functions to `platform.win32.Advapi32`.
+* Add `platform.win32.W32ServiceManager` and `W32Service`.
+* Add Win32 Event Logging functions to `platform.win32.Advapi32` and `platform.win32.Advapi32Util.EventLogIterator`.
+* `platform.win32.Advapi32Util.registryCreateKey` returns `true` if key was created, `false` if it already exists.
+* Add `REG_BINARY`, `REG_EXPAND_SZ` and `REG_MULTI_SZ` support to `platform.win32.Advapi32Util` registry functions.
* Reduce JNI crossings in a number of native methods, moving object creation out into pure Java code.
Bug Fixes
---------
-* Move all native functions into `com.sun.jna.Native</code>, to ensure that all dependent classes must be disposed before the `Native</code> class is unloaded.
-* Fix `platform.win32.Kernel32.GetNativeSystemInfo</code> and `GetSystemInfo</code> AV on Win64.
+* Move all native functions into `com.sun.jna.Native`, to ensure that all dependent classes must be disposed before the `Native` class is unloaded.
+* Fix `platform.win32.Kernel32.GetNativeSystemInfo` and `GetSystemInfo` AV on Win64.
* Fix several potential minor bugs as reported by TvT.
* Fix bug in Structure.StructureSet.toString (Blair Zajac), exposed by Tomcat ThreadLocal cleanup.
* Fix several bugs when using Structure(Pointer) ctor and array fields (Samuel Audet).
@@ -34,40 +34,40 @@ Features
--------
* Add native peer value accessors for Pointer
-* The `jna.library.path</code> property is now re-evaluated whenever a native library is loaded. Previously this value was cached when the JNA classes loaded.
-* `Native.loadLibrary</code> can now load `.drv</code> files.
-* Refactor `com.sun.jna.platform.win32.WINBASE</code> into `WinDef</code>, `WinNT</code> and `BaseTSD</code>, matching Windows SDK headers.
-* Refactor constants from `com.sun.jna.platform.win32.GDI32</code> into `WinGDI</code>, matching Windows SDK headers.
-* Refactor constants from `com.sun.jna.platform.win32.User32</code> into `WinUser</code>, matching Windows SDK headers.
-* Refactor `platform.win32.WinNT.LARGE_INTEGER</code> into a union.
-* Add `platform.win32.ObjBase</code>, `com.sun.jna.platform.win32.Ole32.CoInitializeEx</code>, `CoUninitialize</code>, and `CoCreateInstance</code>.
-* Add `platform.win32.Oleaut32.SysAllocString</code> and `SysFreeString</code>.
-* Add `platform.win32.Secur32.ImpersonateSecurityContext</code> and `RevertSecurityContext</code>.
-* Add `platform.win32.WinNT.WELL_KNOWN_SID_TYPE</code>, `SECURITY_MAX_SID_SIZE</code> and other related SID-related constants.
-* Add `platform.win32.Advapi32.CreateWellKnownSid</code> and `IsWellKnownSid</code> and `com.sun.jna.platform.win32.Advapi32Util.isWellKnownSid</code>.
-* Add `platform.win32.Kernel32.GetVersion</code>, `GetVersionEx</code>, `GetSystemInfo</code>, `GetNativeSystemInfo</code>, `GlobalMemoryStatusEx</code>, `GetLogicalDriveStrings</code> and `IsWow64Process</code>.
-* Add `platform.win32.Kernel32Util.getLogicalDriveStrings</code>.
-* Add `platform.win32.User32.GetSystemMetrics</code>.
-* Add `platform.win32.BaseTSD.DWORD_PTR</code>.
-* Add `platform.win32.WinBase.SYSTEM_INFO</code> and `MEMORYSTATUSEX</code>.
-* Add `platform.win32.WinNT.OSVERSIONINFOEX</code>, `VER</code> constants.
-* Add `platform.win32.WinDef.ULONGLONG</code> and `DWORDLONG</code>.
-* Add `platform.win32.Shell32.SHGetDesktopFolder</code> (prep work for Com4JNA).
-* Add `platform.win32.Winspool.GetPrinterInfo</code>.
-* Add `platform.win32.WinspoolUtil.getPrinterInfo1</code>.
-* Add `platform.win32.GDI32.GetDeviceCaps</code>.
-* Add `platform.win32.GDI32.GetDIBits</code>.
+* The `jna.library.path` property is now re-evaluated whenever a native library is loaded. Previously this value was cached when the JNA classes loaded.
+* `Native.loadLibrary` can now load `.drv` files.
+* Refactor `com.sun.jna.platform.win32.WINBASE` into `WinDef`, `WinNT` and `BaseTSD`, matching Windows SDK headers.
+* Refactor constants from `com.sun.jna.platform.win32.GDI32` into `WinGDI`, matching Windows SDK headers.
+* Refactor constants from `com.sun.jna.platform.win32.User32` into `WinUser`, matching Windows SDK headers.
+* Refactor `platform.win32.WinNT.LARGE_INTEGER` into a union.
+* Add `platform.win32.ObjBase`, `com.sun.jna.platform.win32.Ole32.CoInitializeEx`, `CoUninitialize`, and `CoCreateInstance`.
+* Add `platform.win32.Oleaut32.SysAllocString` and `SysFreeString`.
+* Add `platform.win32.Secur32.ImpersonateSecurityContext` and `RevertSecurityContext`.
+* Add `platform.win32.WinNT.WELL_KNOWN_SID_TYPE`, `SECURITY_MAX_SID_SIZE` and other related SID-related constants.
+* Add `platform.win32.Advapi32.CreateWellKnownSid` and `IsWellKnownSid` and `com.sun.jna.platform.win32.Advapi32Util.isWellKnownSid`.
+* Add `platform.win32.Kernel32.GetVersion`, `GetVersionEx`, `GetSystemInfo`, `GetNativeSystemInfo`, `GlobalMemoryStatusEx`, `GetLogicalDriveStrings` and `IsWow64Process`.
+* Add `platform.win32.Kernel32Util.getLogicalDriveStrings`.
+* Add `platform.win32.User32.GetSystemMetrics`.
+* Add `platform.win32.BaseTSD.DWORD_PTR`.
+* Add `platform.win32.WinBase.SYSTEM_INFO` and `MEMORYSTATUSEX`.
+* Add `platform.win32.WinNT.OSVERSIONINFOEX`, `VER` constants.
+* Add `platform.win32.WinDef.ULONGLONG` and `DWORDLONG`.
+* Add `platform.win32.Shell32.SHGetDesktopFolder` (prep work for Com4JNA).
+* Add `platform.win32.Winspool.GetPrinterInfo`.
+* Add `platform.win32.WinspoolUtil.getPrinterInfo1`.
+* Add `platform.win32.GDI32.GetDeviceCaps`.
+* Add `platform.win32.GDI32.GetDIBits`.
Bug Fixes
---------
-* Fix `ClassCastException</code> in `Structure.equals</code> (<a href="https://jna.dev.java.net/issues/show_bug.cgi?id=152">issue 152</a>).
-* Fix bug initializing a structure object from existing memory when the structure has initialized fields (<a href="https://jna.dev.java.net/issues/show_bug.cgi?id=133">issue 133</a>).
-* Fix NPE reading an array of string from a pointer when an element of the array is `NULL</code> (<a href="https://jna.dev.java.net/issues/show_bug.cgi?id=151">issue 151</a>).
-* Avoid calling `UnregisterNatives</code> in native code (<a href="https://jna.dev.java.net/issues/show_bug.cgi?id=154">issue 154</a>).
-* Compare unpacked library path against canonical (long) filename (<a href="https://jna.dev.java.net/issues/show_bug.cgi?id=156">issue 156</a>).
-* Fix `read()</code> of uninitialized memory in `platform.win32.Advapi32Util.getTokenGroups</code> and `getTokenAccount</code>.
-* Fix `com.sun.jna.platform.win32.Secur32.QuerySecurityContextToken</code> to take a `CtxtHandle</code> instead of `PSecHandle</code>.
+* Fix `ClassCastException` in `Structure.equals` (issue 152).
+* Fix bug initializing a structure object from existing memory when the structure has initialized fields (issue 133).
+* Fix NPE reading an array of string from a pointer when an element of the array is `NULL` (issue 151).
+* Avoid calling `UnregisterNatives` in native code (issue 154).
+* Compare unpacked library path against canonical (long) filename (issue 156).
+* Fix `read()` of uninitialized memory in `platform.win32.Advapi32Util.getTokenGroups` and `getTokenAccount`.
+* Fix `com.sun.jna.platform.win32.Secur32.QuerySecurityContextToken` to take a `CtxtHandle` instead of `PSecHandle`.
* Fix definition of BITMAPINFO (platform/win32).
Release 3.2.5
@@ -92,7 +92,7 @@ Bug Fixes
* Provide String.replace for 1.4 compatibility.
* Avoid allocating memory when Structure is provided a pointer in the ctor.
* Ensure proper value returned in Pointer.getValue() for non-null, unchanged NIO Buffer values.
-* Use 1.4-compatible URI generation (<a href="https://jna.dev.java.net/issues/show_bug.cgi?id=149">issue 149</a>).
+* Use 1.4-compatible URI generation (issue 149).
Release 3.2.4
=============
@@ -102,12 +102,12 @@ Features
* Make Pointer ctor public.
* Provide access to Function objects for arbitrary Pointer values.
-* Add linux/ia64 binaries (bpiwowar). See <a href="https://jna.dev.java.net/issues/show_bug.cgi?id=134">issue 134 patch</a>.
+* Add linux/ia64 binaries (bpiwowar). See issue 134 patch.
Bug Fixes
---------
-* Use a more robust method to decode a file-based URL (<a href="https://jna.dev.java.net/issues/show_bug.cgi?id=135">issue 135</a>).
+* Use a more robust method to decode a file-based URL (issue 135).
Release 3.2.3
=============
@@ -123,12 +123,12 @@ Bug Fixes
* Fix WindowUtils exception on mouse over TrayIcon.
* Fix bug toggling windows transparent/opaque (win32/OSX).
* Avoid overwriting unchanged Pointer values in arrays (function calls with Pointer[] and Structure.read).
-* Ensure Structure fields marked `final</code> are never written.
+* Ensure Structure fields marked `final` are never written.
* Fix bug preventing proper population Structure.ByReference fields on Structure read.
* Ensure double buffering is disabled in components added to a transparent window.
* Fix UnsatisfiedLinkError attempting to load system libraries under Web Start.
* Fix loading Web Start-provided libraries on OSX (libraries must have a .jnilib suffix under Web Start).
-* Properly include sources in Maven zip file (<a href="https://jna.dev.java.net/issues/show_bug.cgi?id=129">Issue 129</a>).
+* Properly include sources in Maven zip file (Issue 129).
Release 3.2.2
=============
@@ -141,7 +141,7 @@ Features
Bug Fixes
---------
-* Fix crash with direct mapping if NULL struct* used (<a href="https://jna.dev.java.net/issues/show_bug.cgi?id=125">Issue 125</a>).
+* Fix crash with direct mapping if NULL struct* used (Issue 125).
* Fix case where null-valued Structure fields would get non-null values on write.
* Synch callback Structure/Structure[] arguments on callback return.
* Fix NPE when mapping an interface to the current process.
@@ -161,8 +161,8 @@ Bug Fixes
---------
* Fix definition of HWND_BROADCAST in W32API.
-* Fix memory alignment checking (<a href="https://jna.dev.java.net/issues/show_bug.cgi?id=121">Issue 121</a>).
-* Fix Structure <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#equals(java.lang.Object)">equals/hashCode</a> implementation, based on current Java fields rather than strictly native memory contents. Avoid using equals/hashCode when avoiding recursive reads/writes.
+* Fix memory alignment checking (Issue 121).
+* Fix Structure equals/hashCode implementation, based on current Java fields rather than strictly native memory contents. Avoid using equals/hashCode when avoiding recursive reads/writes.
Release 3.2.0
=============
@@ -174,13 +174,13 @@ Features
* Optionally throw errno/GetLastError as an exception. This is preferred to (and more efficient than) calling Native.getLastError().
* Unload/delete native library unpacked from jna.jar if Native class is garbage collected. Only install shutdown hook if using the system class loader.
* Auto-write contiguous Structure arrays when first element is written.
-* Support NativeMapped[] as function arguments for interface-mapped libraries (<a href="https://jna.dev.java.net/issues/show_bug.cgi?id=90">Issue 90</a>).
+* Support NativeMapped[] as function arguments for interface-mapped libraries (Issue 90).
* Enable function lookup within current process on Windows.
Bug Fixes
---------
-* Restrict recursive structure reads/writes by thread instead of globally. This avoids potentially missed reads/writes with concurrent access (<a href="https://jna.dev.java.net/issues/show_bug.cgi?id=120">Issue 120</a>).
+* Restrict recursive structure reads/writes by thread instead of globally. This avoids potentially missed reads/writes with concurrent access (Issue 120).
* Ensure Memory is not GC'd and freed if direct NIO buffers mapped to it are extant.
* Allow types derived from java.nio.Buffer as Structure fields.
@@ -192,25 +192,25 @@ Features
* Add raw JNI mapping of static Java methods. Performance is about 10X that of traditional JNA interface mapping, although with less type conversion functionality.
* Add library option to allow passing/return of Java Objects.
-* Allow handling of uncaught callback exceptions (<a href="https://jna.dev.java.net/issues/show_bug.cgi?id=63">Issue 63</a>).
+* Allow handling of uncaught callback exceptions (Issue 63).
* Object oriented interface to X server (see contrib/x11)
* Make Memory class more accessible.
-* Provide Structure ctor with Pointer argument (<a href="https://jna.dev.java.net/issues/show_bug.cgi?id=102">issue 102</a>).
-* Allow implicit library access to current process on linux (<a href="https://jna.dev.java.net/issues/show_bug.cgi?id=98">issue 98</a>).
+* Provide Structure ctor with Pointer argument (issue 102).
+* Allow implicit library access to current process on linux (issue 98).
* Open all shared libraries with RTLD_GLOBAL, if applicable. This was the default behavior on OSX and changes the default behavior on linux.
-* Allow NIO Buffer as Structure field (with limitations) (<a href="https://jna.dev.java.net/issues/show_bug.cgi?id=57">Issue 57</a>)
+* Allow NIO Buffer as Structure field (with limitations) (Issue 57)
* Add `size_t` size.
Bug Fixes
---------
-* Run tests with <a href="http://java.sun.com/j2se/1.4.2/docs/guide/vm/signal-chaining.html">libjsig.so</a>, if available, which fixes some crashes when running tests on 64-bit platforms.
-* Fix <a href="https://jna.dev.java.net/issues/show_bug.cgi?id=104">Issue 104</a>.
-* Fix <a href="https://jna.dev.java.net/issues/show_bug.cgi?id=94">Issue 94</a> (Java 1.6 update 10 regression).
-* Fix <a href="https://jna.dev.java.net/issues/show_bug.cgi?id=51">Issue 51</a> (Java 1.6 update 10 regression).
-* Fix <a href="https://jna.dev.java.net/issues/show_bug.cgi?id=95">Issue 95</a>.
-* Fix <a href="https://jna.dev.java.net/issues/show_bug.cgi?id=101">Issue 101</a>.
-* Fix <a href="https://jna.dev.java.net/issues/show_bug.cgi?id=111">Issue 111</a>, memory leak with String-returning Callback.
+* Run tests with libjsig.so, if available, which fixes some crashes when running tests on 64-bit platforms.
+* Fix Issue 104.
+* Fix Issue 94 (Java 1.6 update 10 regression).
+* Fix Issue 51 (Java 1.6 update 10 regression).
+* Fix Issue 95.
+* Fix Issue 101.
+* Fix Issue 111, memory leak with String-returning Callback.
* Fix missing storage of union type information (affects usage of struct/union by value as argument and return type).
* Remove non-functional Structure ctors requiring explicit size.
@@ -220,7 +220,7 @@ Release 3.0.9
Bug Fixes
---------
-* Fix <a href="https://jna.dev.java.net/issues/show_bug.cgi?id=93">issue 93</a> by only manually searching jna.library.path, then falling back to passing the mapped library name to dlopen/LoadLibrary. This fixes an <a href="http://jira.codehaus.org/browse/JRUBY-3084">issue in JRUBY</a> where the incorrect libc.so.6 was being loaded.
+* Fix issue 93 by only manually searching jna.library.path, then falling back to passing the mapped library name to dlopen/LoadLibrary. This fixes an issue in JRUBY where the incorrect libc.so.6 was being loaded.
Release 3.0.8
==========
View
17 README.md
@@ -1,4 +1,4 @@
-![JNA](https://github.com/twall/jna/raw/master/www/images/jnalogo.jpg "Java Native Access (JNA)")
+![Java Native Access - JNA](https://github.com/twall/jna/raw/master/www/images/jnalogo.jpg "Java Native Access - JNA")
Java Native Access (JNA)
========================
@@ -40,7 +40,7 @@ Features
Community
=========
-* TODO
+All questions should be posted ot the [jna-users Google group](http://groups.google.com/group/jna-users). Issues can be submitted [here on Github](https://github.com/twall/jna/issues).
Using the Library
=================
@@ -50,16 +50,19 @@ Using the Library
* [Using Pointers and Arrays](jna/tree/master/www/PointersAndArrays.md)
* [Using Structures and Unions](jna/tree/master/www/StructuresAndUnions.md)
* [Using By-Reference Arguments](jna/tree/master/www/ByRefArguments.md)
-* [Customization](jna/tree/master/www/Customization.md)
-* [Callbacks/Closures](jna/tree/master/www/Callbacks.md)
-* [JRuby/Jython Usage](jna/tree/master/www/JRubyJython.md)
-* [Frequently Asked Questions (FAQ)](jna/tree/master/www/FAQ.md)
+* [Customization](jna/tree/master/www/CustomMappings.md)
+* [Callbacks/Closures](jna/tree/master/www/CallbacksAndClosures.md)
+* [Dynamically Typed Languages (JRuby/Jython)](jna/tree/master/www/DynamicallyTypedLanguages.md)
+* [Platform Library](jna/tree/master/www/PlatformLibrary.md)
+* [Frequently Asked Questions (FAQ)](jna/tree/master/www/FrequentlyAskedQuestions.md)
* [Direct Method Mapping](jna/tree/master/www/DirectMapping.md)
Contributing
============
-* TODO
+You're encouraged to contribute to JNA. Fork the code from [github.com/twall/jna](https://github.com/twall/jna) and submit pull requests.
+
+If you are interested in paid support, feel free to say so on the [jna-users mailing list](http://groups.google.com/group/jna-users). Most simple questions will be answered on the list, but more complicated work, new features or target platforms can be negotiated with any of the JNA developers (this is how several of JNA's features came into being). You may even encounter other users with the same need and be able to cost share the new development.
License
=======
View
22 www/ByRefArguments.md
@@ -0,0 +1,22 @@
+Using ByReference Arguments
+===========================
+
+When a function accepts a pointer-to-type argument you can use one of the `ByReference` types to capture the returned value, or subclass your own. For example:
+
+ // Original C declaration
+ void allocate_buffer(char **bufp, int* lenp);
+
+ // Equivalent JNA mapping
+ void allocate_buffer(PointerByReference bufp, IntByReference lenp);
+
+ // Usage
+ PointerByReference pref = new PointerByReference();
+ IntByReference iref = new IntByReference();
+ lib.allocate_buffer(pref, iref);
+ Pointer p = pref.getValue();
+ byte[] buffer = p.getByteArray(0, iref.getValue());
+
+Alternatively, you could use a Java array with a single element of the desired type, but the `ByReference` convention better conveys the intent of the code. The `Pointer` class provides a number of accessor methods in addition to `getByteArray()` which effectively function as a typecast onto the memory.
+
+Type-safe pointers may be declared by deriving from the `PointerType` class.
+
View
62 www/CallbacksAndClosures.md
@@ -0,0 +1,62 @@
+Callbacks and Closures
+======================
+
+Callback declarations consist of a simple interface that extends the Callback interface and implements a callback method (or defines a single method of arbitrary name). Callbacks are implemented by wrapping a Java object method in a little bit of C glue code. The simplest usage resembles using anonymous inner classes to register event listeners. Following is an example of callback usage:
+
+ // Original C declarations
+ typedef void (*sig_t)(int);
+ sig_t signal(sig_t);
+
+ // Equivalent JNA mappings
+ public interface CLibrary extends Library {
+ int SIGUSR1 = 30;
+ interface sig_t extends Callback {
+ void invoke(int signal);
+ }
+ sig_t signal(int sig, sig_t fn);
+ int raise(int sig);
+ }
+ ...
+ CLibrary lib = (CLibrary)Native.loadLibrary("c", CLibrary.class);
+ // WARNING: you must keep a reference to the callback object
+ // until you deregister the callback; if the callback object
+ // is garbage-collected, the native callback invocation will
+ // probably crash.
+ CLibrary.sig_t fn = new CLibrary.sig_t() {
+ public void invoke(int sig) {
+ System.out.println("signal " + sig + " was raised");
+ }
+ };
+ CLibrary.sig_t old_handler = lib.signal(CLibrary.SIGUSR1, fn);
+ lib.raise(CLibrary.SIGUSR1);
+ ...
+
+Here is a more involved example, using the Win32 APIs to enumerate all native windows:
+
+ // Original C declarations
+ typedef int (__stdcall *WNDENUMPROC)(void*,void*);
+ int __stdcall EnumWindows(WNDENUMPROC,void*);
+
+ // Equivalent JNA mappings
+ public interface User32 extends StdCallLibrary {
+ interface WNDENUMPROC extends StdCallCallback {
+ /** Return whether to continue enumeration. */
+ boolean callback(Pointer hWnd, Pointer arg);
+ }
+ boolean EnumWindows(WNDENUMPROC lpEnumFunc, Pointer arg);
+ }
+ ...
+ User32 user32 = User32.INSTANCE;
+
+ user32.EnumWindows(new WNDENUMPROC() {
+ int count;
+ public boolean callback(Pointer hWnd, Pointer userData) {
+ System.out.println("Found window " + hWnd + ", total " + ++count);
+ return true;
+ }
+ }, null);
+
+If your callback needs to live beyond the method invocation where it is used, make sure you keep a reference to it or the native code will call back to an empty stub after the callback object is garbage collected.
+
+Proxy wrappers are automatically generated for function pointers found within structs initialized by native code. This facilitates calling those functions from Java.
+
View
9 www/CustomMappings.md
@@ -0,0 +1,9 @@
+Customized Mapping from Java to Native
+======================================
+
+The `TypeMapper` class and related interfaces provide for converting any Java type used as an argument, return value, or structure member to be converted to or from a native type. The example Win32 API interfaces use a type mapper to convert Java boolean into the Win32 BOOL type. A TypeMapper instance is passed as the value for the `TYPE_MAPPER` key in the options map passed to `Native.loadLibrary`.
+
+Alternatively, user-defined types may implement the `NativeMapped` interface, which determines conversion to and from native types on a class-by-class basis.
+
+You may also customize the mapping of Java method names to the corresponding native function name. The `StdCallFunctionMapper` is one implementation which automatically generates stdcall-decorated function names from a Java interface method signature. The mapper should be passed as the value for the `OPTION_FUNCTION_MAPPER` key in the options map passed to the `Native.loadLibrary` call.
+
View
24 www/DirectMapping.md
@@ -0,0 +1,24 @@
+Direct Mapping
+==============
+
+JNA supports a direct mapping method which can improve performance substantially, approaching that of custom JNI. Method signatures are the same as they would be in a JNA interface mapping, but they can be any static or object methods. You only need register them within the static initializer of the defining class, as in the example below. The `Native.register()` method takes the name of your native library, the same as Native.loadLibrary() would.
+
+ import com.sun.jna.*;
+
+ public class HelloWorld {
+
+ static {
+ Native.register(Platform.isWindows() ? "msvcrt" : "m");
+ }
+
+ public static native double cos(double);
+ public static native double sin(double);
+
+ public static void main(String[] args) {
+ System.out.println("cos(0)=" + cos(0));
+ System.out.println("sin(0)=" + sin(0));
+ }
+ }
+
+Direct mapping supports the same type mappings as interface mapping, except for arrays of Pointer/String/WString/NativeMapped as function arguments. You can easily convert from interface mapping to direct mapping by creating a direct mapping class which implements your library interface, with all methods defined as native methods. Then your library instance variable can be assigned an instance of this new class instead of the object returned by `Native.loadLibrary()`.
+
View
37 www/DynamicallyTypedLanguages.md
@@ -0,0 +1,37 @@
+Dynamically Typed Languages
+===========================
+
+Languages such as Jython or JRuby may find it more convenient to access the `NativeLibrary` and Function classes directly rather than establishing a dedicated interface.
+Here's a brief example of using JNA from JRuby:
+
+ require 'java'
+
+ module Libc
+ @@lib = com.sun.jna.NativeLibrary.getInstance("c")
+ @@ptr_funcs = [ 'fopen', 'malloc', 'calloc' ]
+ def self.method_missing(meth, *args)
+ if @@ptr_funcs.include?(meth.to_s)
+ @@lib.getFunction(meth.to_s).invokePointer(args.to_java)
+ else
+ @@lib.getFunction(meth.to_s).invokeInt(args.to_java)
+ end
+ end
+ O_RDONLY = 0
+ O_WRONLY = 1
+ O_RDWR = 2
+ end
+
+ Libc.puts("puts from libc")
+ Libc.printf("Hello %s, from printf\n", "World")
+
+ file = Libc.open("/dev/stdout", 1, Libc::O_WRONLY)
+ n = Libc.write(file, "Test\n", 5)
+ puts "Wrote #{n} bytes via Libc"
+
+ path = "/dev/stdout"
+ fp = Libc.fopen(path, "w+")
+ Libc.fprintf(fp, "fprintf to %s via stdio\n", path)
+ Libc.fflush(fp)
+ Libc.fclose(fp)
+
+
View
135 www/FrequentlyAskedQuestions.md
@@ -0,0 +1,135 @@
+Frequently Asked Questions
+==========================
+
+When should I use Structure.ByReference? Structure.ByValue? Structure[]?
+------------------------------------------------------------------------
+
+Find your corresponding native declaration below:
+
+ typedef struct _simplestruct {
+ int myfield;
+ } simplestruct;
+
+ typedef struct _outerstruct {
+ simplestruct nested; // use Structure
+ } outerstruct;
+
+ typedef struct _outerstruct2 {
+ simplestruct *byref; // use Structure.ByReference
+ } outerstruct2;
+
+ typedef struct _outerstruct3 {
+ simplestruct array[4]; // use Structure[]
+ } outerstruct3;
+
+ typedef struct _outerstruct4 {
+ simplestruct* ptr_array[4]; // use Structure.ByReference[]
+ } outerstruct4;
+
+ // Field is a pointer to an array of struct
+ typedef struct _outerstruct5 {
+ simplestruct* ptr_to_array; // use Structure.ByReference, and use
+ // Structure.toArray() to allocate array
+ } outerstruct5;
+
+ // struct pointers as return value or argument
+ // use Structure
+ outerstruct *myfunc();
+ void myfunc(outerstruct* data);
+
+ // struct (by value) as return value or argument
+ // use Structure.ByValue
+ simplestruct myfunc();
+ void myfunc(simplestruct);
+
+If you need a `ByValue` or `ByReference` class, define them within your main `Structure` definition like this:
+
+ public class MyStructure extends Structure {
+ public static class ByValue extends MyStructure implements Structure.ByValue { }
+ public static class ByReference extends MyStructure implements Structure.ByReference { }
+ }
+
+How do I read back a function's string result?
+----------------------------------------------
+
+Suppose you have a function:
+
+ // Returns the number of characters written to the buffer
+ int getString(char* buffer, int bufsize);
+
+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.
+
+How do I map a native long type?
+--------------------------------
+
+Actually, no one ever asks this question, but they really need the answer. Do not use Java `long`!
+
+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.
+
+My library mapping causes an UnsatisfiedLinkError
+-------------------------------------------------
+
+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.
+
+
+My library sometimes causes a VM crash
+--------------------------------------
+
+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.
+
+My Windows library mapping causes a VM crash on every call
+----------------------------------------------------------
+
+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.
+
+How do I get an arbitrary Pointer value?
+----------------------------------------
+
+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.
+
+`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.
+
+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.
+
+If you really, really, *have* to convert an integer value into a `Pointer`, you can do something like this:
+
+ new IntByReference(value).getPointer().getPointer(0)
+
+Debugging Structure Definitions
+-------------------------------
+
+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.
+
+Does JNA work with J2ME/Windows Mobile?
+---------------------------------------
+
+There is an implementation available, but it has not yet been integrated into the standard build.
+
+I need to use a COM/OCX/ActiveX object. Can JNA do that?
+--------------------------------------------------------
+
+Not really. Try JACOB or com4j, both of which can parse a COM interface definition and generate a Java object to match it.
+
+Why does the VM sometimes crash in my shutdown hook on Windows?
+---------------------------------------------------------------
+
+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.
+
+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.
+
+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.
+
+I get an UnsatisfiedLinkError on OSX when I provide my native library via Java Web Start
+----------------------------------------------------------------------------------------
+
+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.
+
+How does JNA performance compare to custom JNI?
+-----------------------------------------------
+
+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.
+
+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.
+
+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.
+
View
16 www/PlatformLibrary.md
@@ -0,0 +1,16 @@
+Platform Library
+================
+
+JNA includes `platform.jar` that has cross-platform mappings and mappings for a number of commonly used platform functions, including a large number of Win32 mappings as well as a set of utility classes that simplify native access. The code is tested and the utility interfaces ensure that native memory management is taken care of correctly.
+
+Before you map your own functions, check the platform package documentation for an already mapped one.
+
+Platform-specific structures are mapped by header. For example, `ShlObj.h` structures can be found in `com.sun.jna.platform.win32.ShlObj`. Platform functions are mapped by library. For example, `Advapi32.dll` functions can be found in `com.sun.jna.platform.win32.Advapi32`. Simplified interfaces (wrappers) for `Advapi32.dll` functions can be found in `com.sun.jna.platform.win32.Advapi32Util`.
+
+Cross-platform functions and structures are implemented in `com.sun.jna.platform`. These currently include the following.
+
+* `FileMonitor`: a cross-platform file system watcher
+* `FileUtils`: a cross-platform set of file-related functions, such as move to the recycle bin
+* `KeyboardUtils`: a cross-platform set of keyboard functions, such as finding out whether a key is pressed
+* `WindowUtils`: a cross-platform set of window functions, providing non-rectangular shaped and transparent windows.
+

0 comments on commit 8b22412

Please sign in to comment.