Debian Codegraph @

hawtjni-website/src/documentation/developer-guide.md

raw
1 # HawtJNI Developer Guide
2
3 {:toc:2-5}
4
5 ## Features {#features}
6
7 * Automatic mapping from Java to native functions, with simple mappings for all primitive data types
8 * Automatic conversion between C and Java strings
9 * Structure and Union arguments/return values
10 * Function Pointers, (callbacks from native code to Java) as arguments and/or members of a struct
11 * Nested structures
12 * Native long support (32 or 64 bit as appropriate)
13 * Customizable mapping from Java method to native function name
14 * Maven integration:
15 * Generates an autoconf and msbuild projects for the the native library so it can be built on other platforms using the native toolchain.
16 * Native library is built before the test phase, so you can unit tests your JNI classes.
17 * Built native library is packaged as a jar resource and deployed to the Maven repo for easy distribution of native code.
18
19 ## Getting Started with HawtJNI {#getting-started}
20
21 Implementing JNI libraries is a piece of cake when you use HawtJNI. It will code generate
22 the JNI code needed to access the native methods defined in your Java classes. Lets say you
23 wanted to access to the c library's classic `printf` function:
24
25 {pygmentize:: c}
26 int printf(const char *format, ...);
27 {pygmentize}
28
29 To do that, you would only need to define a simple Java class like:
30
31 {pygmentize:: java}
32 import org.fusesource.hawtjni.runtime.*
33
34 @JniClass
35 public class Simple {
36
37 private static final Library LIBRARY = new Library("simple", Simple.class);
38 static {
39 LIBRARY.load();
40 }
41
42 public static native int printf(String message);
43 }
44 {pygmentize}
45
46
47 That's it. No JNI coding required. It's composed of a static class initializer
48 and a native method interface definition for the `printf` function. For folks
49 who have done JNI before this looks familiar except for the way the library is loaded.
50 You could have also loaded the library the traditional textbook way:
51
52 {pygmentize:: java}
53 static {
54 System.loadLibrary("simple");
55 }
56 {pygmentize}
57
58 The benefit of using the Library class to load the native library is that it can
59 automatically unpack the native library from a jar resource and use that so that
60 you don't have to worry installing it to the java library path.
61
62 The HawtJNI build process will take care of implementing your `simple` jni library
63 by using some Maven tooling which we will cover in the next example.
64
65 ### Building with Maven
66
67 If you are not familiar with Maven, please checkout
68 [Maven by Example](http://www.sonatype.com/books/mvnex-book/reference/public-book.html).
69
70 The easiest way to get started with HawtJNI is copy and use
71 [the example Maven project](http://github.com/fusesource/hawtjni/tree/master/hawtjni-example/) as a template for your module.
72
73 At the root of the Maven project run:
74 {pygmentize:: text}
75 mvn install
76 {pygmentize}
77
78 The Maven build will produce the following artifacts:
79
80 * `target/${artifactId}-${version}.jar`: is the standard jar which Maven produces that contains all your java classes.
81 * `target/${artifactId}-${version}-native-src.zip`: is a source archive of
82 a autoconf and msbuild based build project for the native library. You can
83 easily build this on other platforms using the platforms native toolchain.
84 * `target/${artifactId}-${version}-${platform}.jar` is the platform specific
85 jar which contains the your build JNI library as a resource.
86
87 These artifacts will be deployed to the Maven repository so that other users can
88 easily use them as dependencies in their builds.
89
90 You may also be interesting in
91 [How to Add HawtJNI to an Existing Maven Build](#adding-to-maven-build).
92
93 ## Mapping Native Methods {#method-mapping}
94 ### Overview
95
96 HawtJNI looks for all classes annotated with `@JniClass`. For every static
97 native method found, it will generate the corresponding JNI function which calls
98 a the platform function of the same name as the java method.
99
100 <!-- TODO: Cover these JniClass flags
101
102 /**
103 * Indicate that the platform source is in C++
104 */
105 CPP,
106 -->
107
108 The JNI method mapping can be customized by applying the `@JniMethod` annotation
109 to the method and the `@JniArg` to each method argument.
110
111 <!-- TODO: Cover these JniMethod flags
112 /**
113 * Indicate that the item should not be generated. For example,
114 * custom natives are coded by hand.
115 */
116 METHOD_SKIP,
117
118 /**
119 * Indicate that a native method should be looked up dynamically. It
120 * is useful when having a dependence on a given library is not
121 * desirable. The library name is specified in the *_custom.h file.
122 */
123 DYNAMIC,
124
125 /**
126 * Indicate that the native method represents a constant or global
127 * variable instead of a function. This omits () from the generated
128 * code.
129 */
130 CONSTANT_GETTER,
131
132 /**
133 * Indicate that the C function should be casted to a prototype
134 * generated from the parameters of the native method. Useful for
135 * variable argument C functions.
136 */
137 CAST,
138
139 /**
140 * Indicate that the native is part of the Java Native Interface. For
141 * example: NewGlobalRef().
142 */
143 JNI,
144
145 /**
146 * Indicate that the native method represents a structure global
147 * variable and the address of it should be returned to Java. This is
148 * done by prepending &.
149 */
150 ADDRESS,
151
152 /**
153 * Indicate that the platform source is in C++
154 */
155 CPP,
156
157 /**
158 * Indicate that the native method is a C++ constructor that allocates
159 * an object on the heap.
160 */
161 CPP_NEW,
162
163 /**
164 * Indicate that the native method is a C++ destructor that
165 * deallocates an object from the heap.
166 */
167 CPP_DELETE,
168
169 /**
170 * Indicate that the native method is a C# constructor that allocates
171 * an object on the managed (i.e. garbage collected) heap.
172 */
173 CS_NEW,
174
175 /**
176 * Indicate that the native method's return value is a
177 * C# managed object.
178 */
179 CS_OBJECT,
180
181 /**
182 * Indicate that the native method takes 2 arguments, a collection and
183 * an item, and the += operator is used to add the item to the
184 * collection.
185 */
186 ADDER,
187 -->
188
189 Without additional configuration native methods automatically convert the
190 method arguments and return types to the corresponding type of the
191 same size on the platform.
192
193 {filter::textile}
194 || Java Type || Native Type || Description || Windows Types ||
195 | <code>byte</code> | <code>char</code> | 8-bit integer | <code>BYTE</code>, <code>TCHAR</code> |
196 | <code>short</code> | <code>short</code> | 16-bit integer | <code>WORD</code> |
197 | <code>char</code> | <code>wchar_t</code> | 16 or 32-bit character | <code>TCHAR</code> |
198 | <code>int</code> | <code>int</code> | 32-bit integer | <code>DWORD</code> |
199 | <code>long</code> | <code>long long</code> | 64-bit integer | <code>LONG</code> |
200 | <code>boolean</code> | <code>int</code> | boolean value | <code>BOOL</code> |
201 | <code>float</code> | <code>float</code> | 32-bit FP | |
202 | <code>double</code> | <code>double</code> | 64-bit FP | |
203 {filter}
204
205 If a primitive array type or String is used, it gets converted to the corresponding
206 native array/pointer type.
207
208 {filter::textile}
209 || Java Type || Native Type || Description || Windows Types ||
210 | <code>byte[]</code> | <code>char*</code> | 8-bit array | <code>BYTE</code>, <code>TCHAR</code> |
211 | <code>short[]</code> | <code>short*</code> | 16-bit array | <code>WORD</code> |
212 | <code>char[]</code> | <code>wchar_t*</code> | 16 or 32-bit array | <code>TCHAR</code> |
213 | <code>int[]</code> | <code>int*</code> | 32-bit array | <code>DWORD</code> |
214 | <code>long[]</code> | <code>long long*</code> | 64-bit array | <code>LONG</code> |
215 | <code>float[]</code> | <code>float*</code> | 32-bit FP array | |
216 | <code>double[]</code> | <code>double*</code> | 64-bit FP array | |
217 | <code>String</code> | <code>char*</code> | 8-bit array | <code>LPTCSTR</code> |
218 {filter}
219
220 It's important to note that when dealing with arrays and structures, HawtJNI must
221 copy the contents of the java object to the native type since the JVM can any
222 time move java objects in memory. It will then call the native function and then
223 copy back the native array back over the original java array so that the original
224 java array picks up any changes.
225
226 When a Java string is converted to a `char *` it applies a UTF-8 conversion. If your
227 native code can handle wide character (i.e. double byte unicode characters), then you
228 annotate the argument with `UNICODE` flag. For example:
229
230 {pygmentize:: java}
231 public static native int printf(
232 @JniArg(flags={UNICODE}) String message);
233 {pygmentize}
234
235 ### Passing Primitives by Reference
236
237 It is common to run into native methods similar to the following:
238 {pygmentize:: c}
239 void adder(int *result, int left, int right) {
240 *result = left + right;
241 }
242 {pygmentize}
243
244 They use a pointer to a simple type to store the result of function call. It may
245 not be obvious at first, but this can be mapped in java using a primitive array.
246 For example:
247 {pygmentize:: java}
248 public static native void adder(int []result, int left, int right);
249 {pygmentize}
250
251 Just make sure you use the method with 1 element array:
252 {pygmentize:: java}
253 byte[] result = new byte[1];
254 adder(result, 3, 4);
255 System.out.println("The result was: "+result[0]);
256 {pygmentize}
257
258 ## Mapping Native Structures {#mapping-native-structures}
259
260 You define a Java class for each native structure that you want map and
261 replicate all the fields that you will need to access as regular java fields.
262
263 For example, say you had a C structure and function that was defined as follows:
264 {pygmentize:: c}
265 struct COORD {
266 int x;
267 int y;
268 };
269 void display_coord(struct COORD* position);
270 {pygmentize}
271
272 Then the the corresponding Java class for the structure would look like:
273
274 {pygmentize:: java}
275 @JniClass(flags={STRUCT})
276 public static class COORD {
277 public short x;
278 public short y;
279 }
280 {pygmentize}
281
282 The native method definition can then just take COORD java object as an argument.
283 {pygmentize:: java}
284 public static native void display_coord(COORD position);
285 {pygmentize}
286
287 ### Nested Structures
288
289 Nested native structures are also easy. For example:
290
291 {pygmentize:: c}
292 struct RECT {
293 struct COORD top_left;
294 struct COORD bottom_right;
295 };
296 {pygmentize}
297
298 Would be mapped as:
299 {pygmentize:: java}
300 @JniClass(flags={STRUCT})
301 public static class RECT {
302 public COORD top_left = new COORD();
303 public COORD bottom_right = new COORD();
304 }
305 {pygmentize}
306
307 ### Passing Structures By Value
308
309 You probably noticed that structures are passed by reference by default. If your
310 native method accepts the structure by value instead, then you need to annotate the method argument with the `BY_VALUE` flag.
311
312 For example, if your native method was defined as:
313 {pygmentize:: c}
314 int validate_coord(struct COORD position);
315 {pygmentize}
316
317 Then your Java method mapping would look like
318 {pygmentize:: java}
319 public static native int validate_coord(
320 @JniArg(flags={BY_VALUE}) COORD position);
321 {pygmentize}
322
323 The passed object MUST not be `null`.
324
325 ### Using Typedefed Structures
326
327 If the structure name your mapping is actually a typedef, in other words, the type is referred to in native code by just the plain `name` and not the `struct name`, then you need to add the `TYPEDEF` flag to struct definition.
328
329 For example, if the native definition was:
330 {pygmentize:: c}
331 typedef struct _COORD {
332 int x;
333 int y;
334 } COORD;
335 {pygmentize}
336
337 Then the the corresponding Java class for the structure would look like:
338
339 {pygmentize:: java}
340 @JniClass(flags={STRUCT,TYPEDEF})
341 public static class COORD {
342 public short x;
343 public short y;
344 }
345 {pygmentize}
346
347 ### Zero Out Structures
348
349 You do NOT have to map all the native fields in a structure it's corresponding Java structure class. You will actually get better performance if you only map the fields that will be accessed by your Java application.
350
351 If not all the fields of the structure are mapped, then when the native structure is created from a Java structure, the unmapped fields will have whatever random data was in the allocated memory location the native structure was allocated on. If you prefer or NEED to zero out unmapped fields, then add the `ZERO_OUT` flag. For example:
352
353 {pygmentize:: java}
354 @JniClass(flags={STRUCT,ZERO_OUT})
355 public static class COORD {
356 public short x;
357 }
358 {pygmentize}
359
360 ### Skipping Fields
361
362 If you need to have a Java field which is not mapped to a native structure field, annotate it with `@JniField(flags={FIELD_SKIP})`. This can be useful,
363 to holding java side computations of the structure.
364
365 For example, if you want to cache the hash computation of the structure you could do the following:
366 {pygmentize:: java}
367 @JniClass(flags={STRUCT,ZERO_OUT})
368 public static class COORD {
369 public short x;
370 public short y;
371
372 @JniField(flags={FIELD_SKIP})
373 public int hash;
374 public int hashCode() {
375 if( hash==0 ) {
376 hash = (x << 16) & y;
377 }
378 return hash;
379 }
380 }
381 {pygmentize}
382
383 ## Binding to C++ Classes
384
385 HawtJNI support binding to C++ classes. Here's an example of bind to the "std::string" class.
386
387 {pygmentize:: java}
388 @JniClass(name="std::string", flags={ClassFlag.CPP})
389 private static class StdString {
390
391 @JniMethod(flags={CPP_NEW})
392 public static final native long create();
393
394 @JniMethod(flags={CPP_NEW})
395 public static final native long create(String value);
396
397 @JniMethod(flags={CPP_DELETE})
398 static final native void delete(long self);
399
400 @JniMethod(flags={CPP_METHOD}, cast="const char*")
401 public static final native long c_str_ptr (long self);
402
403 @JniMethod(flags={CPP_METHOD}, cast="size_t")
404 public static final native long length (long self);
405 }
406 {pygmentize}
407
408 The `CPP_NEW` flagged methods are constructor methods. They allocate
409 a new instance of the class or structure on the native heap and return
410 a pointer to it.
411
412 The `CPP_DELETE` flagged method is used to destruct a previously created object.
413 The `CPP_METHOD` flagged methods are used to call methods on the object.
414
415 You can also get and set fields on the object using the `GETTER` and `SETTER`
416 method flags. For example, if we had an object with a `int count` field.
417
418 {pygmentize:: java}
419 @JniMethod(flags={GETTER})
420 public static final native int count(long self);
421
422 @JniMethod(flags={SETTER})
423 public static final native void count(long self, int value);
424 {pygmentize}
425
426 Notice that the `CPP_DELETE`, `CPP_METHOD`, `GETTER`, and `SETTER` all take
427 a pointer the object they operating against as the first argument of the java
428 method definition.
429
430 ## Advanced Mapping Topics
431
432 ### Loading Constants {#platform-constants}
433
434 Many times you need to access the value of platform constants. To load
435 platform constants you will need to:
436
437 1. Define a constant initializer method which when called will sets all the
438 static fields annotated as constant fields with the constant value. Example:
439 {pygmentize:: java}
440 @JniMethod(flags={CONSTANT_INITIALIZER})
441 private static final native void init();
442 {pygmentize}
443
444 2. For each constant you want to load define a static field for it with the
445 `@JniField(flags={CONSTANT})` annotation. Example:
446 {pygmentize:: java}
447 @JniField(flags={CONSTANT})
448 public static short FOREGROUND_BLUE;
449 {pygmentize}
450
451 3. Call the constant initializer method in the class initializer, after the
452 library is loaded. For example:
453 {pygmentize:: java}
454 private static final Library LIBRARY = new Library("simple", Simple.class);
455 static {
456 LIBRARY.load();
457 init();
458 }
459 {pygmentize}
460
461
462 ### Renaming {#accessors}
463
464 If you want to call your java method something different from the native method
465 name, you can set the `accessor` attribute on a `@JniMethod` or `@JniField` annotation.
466
467 For example, to call the native `printf` function from a Java `print` method,
468 you would set it up as follows:
469 {pygmentize:: java}
470 @JniMethod(accessor="printf")
471 public static native int print(String message);
472 {pygmentize}
473
474 In the case of field on a structure this can be used to do simple renames or
475 to map field to the field of a nested structure or union:
476 {pygmentize:: java}
477
478 // Just a simple rename..
479 @JniField(accessor="dwSize")
480 public int size;
481
482 // Mapping to a nested field.
483 @JniField(accessor="u.pos")
484 public int deep;
485
486 {pygmentize}
487
488 The accessor also comes in handy when you want to load constants which
489 are not a simple symbol, for example the size of a structure:
490 {pygmentize:: java}
491 @JniField(accessor="sizeof(struct COORD)", flags={CONSTANT})
492 public static int SIZEOF_COORD;
493 {pygmentize}
494
495 ### Pointers {#pointers}
496
497 If you want the same java class to be able to work with 32 bit and 64 bit
498 pointers, you should map pointers to Java `long`. If your only targeting 32 bit
499 platforms you can map pointers to `int`.
500
501 When HawtJNI is on a 32 bit platform but is mapping pointers to Java's 64 bit
502 longs, it needs to know that the value it's working with is a pointer so that it
503 properly up and down casts the pointer value.
504
505 This is typically done by setting the `cast` attribute on the the `@JniMethod`,
506 `@JniArg` and `@JniField` annotations to the pointer type. In general it's good
507 practice to set the cast attribute to the defined type of value.
508
509 For example, to let HawtJNI know that the `malloc` function returns a void
510 pointer you would define it as follows:
511 {pygmentize:: java}
512 @JniMethod(cast="void *")
513 public static final native long malloc(
514 @JniArg(cast="size_t") long size);
515 {pygmentize}
516
517 If the cast end with `*` and it's being mapped to a Java `long` then HawtJNI knows that it's dealing with a pointer type. But if your using a typedef to pointer, then you need to flag the condition with one of the following:
518
519 * `@JniMethod(flag={POINTER_RETURN})`
520 * `@JniArg(flags={POINTER_ARG})`
521 * `@JniField(flags={POINTER_FIELD})`
522
523 This is very common on the Windows platform where tend to typedef pointer types like `LPTCSTR`.
524
525 You may be tempted to do pointer arithmetic on the java side long value, but DON'T. The native pointer is a combination of signed/unsigned, and 32/64 bit value which may more may not match java's memory model. Adding offsets to the pointer on the java side will likely result in a invalid pointer location.
526
527 ### Using the Native Heap {#heap-structures}
528
529 The memory associated with a passed structure or array is reclaimed at the end of every native method call. Therefore, a method expects a passed array or structure reference to remain valid after the method call then that array or structure needs to be allocated on the native heap instead.
530
531 This is accomplished using the standard native `malloc` function call.
532 For example to create a char array 80 bytes big:
533
534 {pygmentize:: java}
535 long buffer = malloc(80);
536 {pygmentize}
537
538 To create a structure on the the heap, your going to need a couple of helper methods.
539
540 1. You need to know the size of the structure.
541 2. You need define a versions of memmove which copy to and from the your Java structure object and memory buffer (`void *`).
542
543 I recommend keeping those defined in the structure class itself. For example:
544
545 {pygmentize:: java}
546 @JniClass(flags={STRUCT})
547 public static class COORD {
548
549 public short x;
550 public short y;
551
552 // To hand loading the SIZE_OF constant
553 @JniMethod(flags={CONSTANT_INITIALIZER})
554 private static final native void init();
555 @JniField(flags={CONSTANT}, accessor="sizeof(struct COORD)")
556 public static short SIZE_OF;
557 static {
558 init();
559 }
560
561 public static final native void memmove (
562 @JniArg(cast="void *", flags={NO_IN, CRITICAL})) COORD dest,
563 @JniArg(cast="const void *", flags={NO_OUT, CRITICAL}) long src,
564 @JniArg(cast="size_t") long size);
565
566 public static final native void memmove (
567 @JniArg(cast="void *", flags={NO_IN, CRITICAL})) long dest,
568 @JniArg(cast="const void *", flags={NO_OUT, CRITICAL}) COORD src,
569 @JniArg(cast="size_t") long size);
570 }
571 {pygmentize}
572
573 Now you can allocate and initialize a structure on the heap:
574 {pygmentize:: java}
575 long buffer = malloc(COORD.SIZE_OF);
576 COORD tmp = new COORD()
577 tmp.x = 3;
578 tmp.y = 4;
579 COORD.memmove(buffer, tmp, COORD.SIZE_OF);
580 {pygmentize}
581
582 <!-- TODO: talk about pointer arithmetic to index into an array of structs -->
583
584 ### Callbacks: Calling Java methods from native functions.
585
586 Some native functions require a callback function pointer as an argument. You can
587 create one using a `Callback` object. For example, lets say needed to call the following
588 native function:
589
590 {pygmentize:: java}
591 long foo(void (*fp)(char *buffer, int n));
592 {pygmentize}
593
594 It you could map it in Java as:
595 {pygmentize:: java}
596 public static final native void foo (
597 @JniArg(cast="void *") long fp);
598 {pygmentize}
599
600 Next you need to create a java method that can accept the callback. The method MUST
601 return long and can have any number of arguments, but they must also all be longs.
602 The method can be a static or instance method.
603
604 For example:
605 {pygmentize:: java}
606 class MyObject {
607 public long mymethod(long buffer, long n) {
608 System.out.println("Was given a buffer "+n+" byte big at "+buffer);
609 }
610 }
611 {pygmentize}
612
613 Then to create a function pointer which points back to a Java method, you create
614 a Callback object with a reference to the Java object, method name, and number of arguments
615 on the method takes.
616
617 For example:
618 {pygmentize:: java}
619 MyObject object = new MyObject();
620 Callback callback = new Callback(object, "mymethod", 2);
621 long fp = callback.getAddress();
622 foo(fp);
623 {pygmentize}
624
625 Warning: you can only create up to 128 Callbacks concurrently. If you exceed this number
626 `callback.getAddress()` returns zero. You should use the `callback.dispose()` method
627 to release a callback once it's not being used anymore.
628
629 ### Attaching Native Threads to the JVM
630
631 If you have a thread that was not started by the JVM try to call into the
632 JVM you must first "attach" it to the JVM. HawtDispatch provides some helper
633 methods to make it simpler and more efficient. These methods are only available
634 on JVMs supporting JNI 1.2.
635
636 * `jint hawtjni_attach_thread(JNIEnv **env, const char *thread_name);`
637 * `jint hawtjni_detach_thread();`
638
639 If your platform supports pthreads and you have the `HAVE_PTHREAD_H` define enabled,
640 then the attach operation is cached and the detach is only performed when the
641 thread stops.
642
643 ### Optimizations {#optimizations}
644
645 If you have performance sensitive method that works on an Array or Structure,
646 setting on of the following flags may help your performance.
647
648 * __`@JniArg(flags={NO_IN})`__:Indicate that a native method parameter is an out
649 only variable. This only makes sense if the parameter is a structure or an
650 array of primitives. It is an optimization to avoid copying the java memory to
651 C memory on the way in.
652
653 * __`@JniArg(flags={NO_OUT})`__: Indicate that a native method parameter is an in
654 only variable. This only makes sense if the parameter is a structure or an
655 array of primitives. It is an optimization to avoid copying the C memory from
656 java memory on the way out.
657
658 * __`@JniArg(flags={CRITICAL})`__: Uses a special JVM call which locks the java
659 array in memory and disable garbage collection for the duration of the native
660 call. This is an optimization to avoid copying memory and must only be used
661 with low latency functions. This only makes sense if the parameter is an array
662
663 These optimization flags are typically used for the `memmove` C library function.
664 for example, to copy the the contents of a `byte[]` into a java `int[]`, you would
665 define the `memmove` method as follows:
666
667 {pygmentize:: java}
668 public static final native void memmove (
669 @JniArg(cast="void *", flags={NO_IN, CRITICAL})) int[] dest,
670 @JniArg(cast="const void *", flags={NO_OUT, CRITICAL}) byte[] src,
671 @JniArg(cast="size_t") long size);
672 {pygmentize}
673
674
675 ### Conditionals {#conditionals}
676
677 You can use the `conditional` attribute on the `@JniClass`, `@JniMethod` and `@JniField` annotations to control if JNI code associated
678 with the class, method, or field gets conditionally compiled out.
679
680 This is very useful if your mapping to a native function, structure, or field
681 that may not be available on all the platforms which your Java class is going to
682 be made available to.
683
684 Example:
685 {pygmentize:: java}
686 @JniMethod(conditional="defined(_WIN32)")
687 public static native int printf(String message);
688 {pygmentize}
689
690 Would produce a JNI `printf` method implementation which is surrounded by the
691 following pre-processor directives:
692
693 {pygmentize:: c}
694 #if defined(_WIN32)
695 // ... the JNI method implementation would be here
696 #endif
697 {pygmentize}
698
699 The `conditional` on a `@JniMethod` or `@JniField` defaults to value configured on
700 the enclosing `@JniClass`. So if most of the fields or methods in a class need to
701 have have the same conditional applied, just set it on the `@JniClass` annotation.
702
703 ## Maven Plugin Reference {#adding-to-maven-build}
704
705 The HawtJNI provides a Maven plugin which makes it easy code generate and build
706 the native library for your current platform.
707
708 The Maven tooling takes care of:
709
710 * Generating the native JNI source code from your annotated Java code
711 * Generating a GNU make and MS Build compatible source project for building the native library
712 * Attaches the source project as `native-src.zip` artifact to the Maven build
713 * Kicking of a native build of the library using the platform's build tools
714 * Packages the native library in a `platform.jar` and attaches the artifact to the Maven build.
715 * Updates the test build path so that unit tests can use the build native library.
716
717 ### Usage
718
719 Once you have a working Maven build for a java module, you can then update it to
720 use HawtJNI to generate your JNI libraries. With the following steps:
721
722 1. Add the `hawtjni-runtime` dependency to pom. This small 19k jar file contains the HawtJNI annotations and a few helper classes that
723 you will be developing against.
724 {pygmentize:: xml}
725 <pom>
726 <dependencies>
727 ...
728 <dependency>
729 <groupId>org.fusesource.hawtjni</groupId>
730 <artifactId>hawtjni-runtime</artifactId>
731 <version>${project_version}</version>
732 </dependency>
733 ...
734 </dependencies>
735 <pom>
736 {pygmentize}
737
738 2. Add the HawtJNI Maven plugin to the pom.
739 {pygmentize:: xml}
740 <project>
741 <build>
742 <plugins>
743 ...
744 <plugin>
745 <groupId>org.fusesource.hawtjni</groupId>
746 <artifactId>hawtjni-maven-plugin</artifactId><!-- was maven-hawtjni-plugin until 1.15 -->
747 <version>${project_version}</version>
748 <executions>
749 <execution>
750 <goals>
751 <goal>generate</goal>
752 <goal>build</goal>
753 <goal>package-jar</goal>
754 <goal>package-source</goal>
755 </goals>
756 </execution>
757 </executions>
758 </plugin>
759 ...
760 </plugins>
761 </build>
762 <project>
763 {pygmentize}
764
765 ### Build Phases
766
767 You may have noticed that HawtJNI is generating a slew of code in different
768 directories. Here is a breakdown of what gets generated where and during which
769 Maven build phase:
770
771 1. __process-classes__: Processes the annotated java classes:
772
773 1. generates JNI .c and .h files to
774 `target/generated-sources/hawtjni/native-src`
775
776 2. generates an autoconf and msbuild build project in the
777 `target/generated-sources/hawtjni/native-package` directory
778
779 2. __generate-test-resources__: Compiles the native library:
780
781 1. The project is built in `target/native-build`
782
783 2. The project installed the libraries to `target/native-dist`
784
785 3. The libraries are copied to `target/generated-sources/hawtjni/lib` which gets
786 added as a test resource path.
787
788 3. __package-jar__: The contents of `target/generated-sources/hawtjni/lib` get
789 jarred and attached to the Maven build with a platform specific classifier.
790
791 4. __package-source__: The contents of
792 `target/generated-sources/hawtjni/native-package` get zipped up into a platform
793 agnostic source package for building the native library.
794
795 ## Platform Build Tools Requirements
796
797 ### macOS
798
799 Use brew to install the necessary tools:
800
801 brew install automake autoconf libtool gcc
802
803 Make sure the GCC compiler is used by default:
804
805 cd /usr/local/bin
806 ln -s c++-9 c++
807 ln -s cpp-9 cpp
808 ln -s g++-9 g++
809 ln -s gcc-9 gcc
810 export PATH=/usr/local/bin:$PATH
811 rehash
812
813 ### Windows
814
815 Download and install the free [Microsoft Windows SDK][ms_sdk]. The SDK includes
816 all the headers, libraries, and build tools needed to compile the JNI library.
817
818 Set the `JAVA_HOME` environment variable to the location where your JDK is
819 installed.
820
821 Make sure the `msbuild` (`vcbuild` for legacy SDK versions) tool is on in your system PATH. The simplest way
822 is to use SDK command prompt.
823
824 [ms_sdk]: https://developer.microsoft.com/en-us/windows/downloads
825
826 ### Ubuntu Linux
827
828 On Ubuntu you need a JDK and the `build-essential` package installed to do
829 native library builds.
830
831 If you want to be able to generate the `native-src.zip` which contains a GNU style
832 make project, then you will also need the following packages installed:
833
834 * automake1.10
835 * libtool
836
837 Install them is by running:
838
839 sudo apt-get install build-essential automake1.10 libtool
840
841 ### Fedora Core Linux
842
843 On Ubuntu you need a JDK and the and gcc package installed to do
844 native library builds.
845
846 Install them is by running:
847
848 yum install gcc java-1.6.0-openjdk-devel
849
850 If you want to be able to generate the `native-src.zip` which contains a GNU style
851 make project, then you will also need the following packages installed:
852
853 * automake
854 * libtool
855
856 Install them is by running:
857
858 yum install automake libtool
859
860 <!-- TODO:
861 ### Using Autoconf to Detect Platform Features
862
863 ### custom header files ... linking
864 -->
865