diff --git a/sites/cheerpj/src/content/docs/11-guides/implementing-native-libraries.md b/sites/cheerpj/src/content/docs/11-guides/implementing-native-libraries.md index d1c7d5bc..f3082dbe 100644 --- a/sites/cheerpj/src/content/docs/11-guides/implementing-native-libraries.md +++ b/sites/cheerpj/src/content/docs/11-guides/implementing-native-libraries.md @@ -19,11 +19,11 @@ CheerpJ adapts this concept to load JavaScript modules, using the same `System.l In general, we can implement native libraries in CheerpJ by following these steps: -1. Create a JavaScript module 'native.js' that implements the native methods. +1. Create a JavaScript module that implements the native methods. 2. Create a Java class that loads the native library and declares the native methods. 3. Load the native library in the Java class with CheerpJ. -## Loading and Implementing a Native Library with CheerpJ +### Creating a JavaScript Module JavaScript functions that implement native methods should follow a specific naming convention - `Java__`. For instance, if `com.foo.Bar` has a native method called `baz`, the function will be called `Java_com_foo_Bar_baz` @@ -44,7 +44,23 @@ async function Java__(lib, self, param1 > [!info] Handling Static Native Methods > If the native method is static, the `self` parameter can be omitted. -## Initializing CheerpJ with the `javaProperties` Option +### Native Methods in Java + +To declare a native method in Java, use the `native` keyword in the method declaration. The method is defined in the Java class but is not implemented in Java. Instead, the implementation will be provided in the native library JavaScript module which is loaded with `System.loadLibrary`. + +```java +public class ClassName { + // Load the library file + static { + System.loadLibrary(""); + } + + // Native method declaration + private native void methodName(param1, param2, ...); +} +``` + +### Initializing CheerpJ with the `javaProperties` Option To use a native library in CheerpJ, you need to set the `java.library.path` property to the directory containing the JavaScript file that implements the native methods. This is done by passing the `javaProperties` option to the `cheerpjInit` function: @@ -62,6 +78,7 @@ In the following example, we’ll see how to create a native library in JavaScri ```java title="Example.java" public class Example { + // Load the native.js library file static { System.loadLibrary("native"); } @@ -70,6 +87,7 @@ public class Example { new Example().alert("Hello, world!"); } + // Native method declaration private native void alert(String message); } ```