The launcher provides the ability to bind Windows API functions to java native
methods without the need to write any native code. This is best described with
a simple example:
package org.boris.winrun4j.test;
import org.boris.winrun4j.PInvoke;
import org.boris.winrun4j.PInvoke.DllImport;
import org.boris.winrun4j.PInvoke.UIntPtr;
public class BindingExample1
{
static {
PInvoke.bind(BindingExample1.class);
}
@DllImport("kernel32")
public static native boolean GetComputerName(StringBuilder lpBuffer, UIntPtr lpnSize);
public static void main(String[] args) throws Exception {
StringBuilder name = new StringBuilder();
UIntPtr size = new UIntPtr(100);
if (GetComputerName(name, size)) {
System.out.println(name);
}
}
}
When the class is loaded the PInvoke method will bind all java methods with the DllImport to a native function.
When the native method is invoked the java arguments will be automatically converted into native values.
Native memory will be managed automatically.
The example above is equivalent to the information/instructions provided on PINVOKE.NET for
GetComputerName.
The only extra step required is the
PInvoke.bind
call in the static constructor.
The "lpnSize" parameter tells the native binder how much space to allocate to the "lpBuffer" string.
The goal of the native binder is to be as compatible with
PINVOKE.NET as possible
so that it can be used as the reference. Some differences do exist due to language constraints, such as:
- The native methods must be manually bound by using the
PInvoke.bind
method. The simplest
approach is use a static constructor as above.
- The java "long" primitive type should be used where an [in] pointer or handle is required. It is interpreted
by the native binder to mean the native pointer size (ie. it will work on both 32-bit and 64-bit VMs).