Skip to content

Commit

Permalink
updated the guide after review
Browse files Browse the repository at this point in the history
  • Loading branch information
theodoravraimakis committed Nov 18, 2024
1 parent c551adc commit de49d88
Showing 1 changed file with 21 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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_<fully-qualified-class-name>_<method-name>`. For instance, if `com.foo.Bar` has a native method called `baz`, the function will be called `Java_com_foo_Bar_baz`

Expand All @@ -44,7 +44,23 @@ async function Java_<fully-qualified-class-name>_<method-name>(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("<library-name>");
}

// 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:

Expand All @@ -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");
}
Expand All @@ -70,6 +87,7 @@ public class Example {
new Example().alert("Hello, world!");
}

// Native method declaration
private native void alert(String message);
}
```
Expand Down

0 comments on commit de49d88

Please sign in to comment.