Skip to content

Commit 6e7c71a

Browse files
committed
Explain importing Java functions in C
1 parent d77302f commit 6e7c71a

File tree

1 file changed

+63
-0
lines changed
  • graalwasm/graalwasm-embed-c-code-guide

1 file changed

+63
-0
lines changed

graalwasm/graalwasm-embed-c-code-guide/README.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,69 @@ public class App {
180180
}
181181
```
182182

183+
## 4. Using Java functions from WebAssembly
184+
185+
You can also call Java functions from WebAssembly by importing them in your WebAssembly modules.
186+
For the sake of an example, let's try to move the logic which computes the next element of the output (by doing an integer increment) to a Java function.
187+
188+
Here is what we will need to add to our C file to declare an external function whose implementation we will provide in Java:
189+
190+
```c
191+
extern int javaInc(int number)
192+
__attribute__((
193+
__import_module__("env"),
194+
__import_name__("java-increment"),
195+
));
196+
```
197+
198+
This introduces an import in the resulting WebAssembly module.
199+
The import will try to pull a function named `java-increment` from the imported module `env`.
200+
Within our C code, this function will be available under the name `javaInc`.
201+
We can update our `floyd` function to use `javaInc` like so:
202+
203+
```c
204+
void floyd(int rows) {
205+
int number = 1;
206+
for (int i = 1; i <= rows; i++) {
207+
for (int j = 1; j <= i; j++) {
208+
printf("%d ", number);
209+
number = javaInc(number);
210+
}
211+
printf(".\n");
212+
}
213+
}
214+
```
215+
216+
Then, in our Java application, we pass in an import object when instantiating our WebAssembly module.
217+
This import object maps module names to module objects, with each module object mapping function names to function definitions.
218+
219+
```java
220+
...
221+
import java.util.Map;
222+
import org.graalvm.polyglot.proxy.ProxyExecutable;
223+
import org.graalvm.polyglot.proxy.ProxyObject;
224+
225+
public class App {
226+
227+
public static Object javaIncrement(Value... v) {
228+
return Value.asValue(v[0].asInt() + 1);
229+
}
230+
231+
public static void main(String[] args) throws IOException {
232+
...
233+
// Compile and instantiate the module with host function
234+
Value module = context.eval(source);
235+
Value instance = module.newInstance(ProxyObject.fromMap(
236+
Map.of("env", ProxyObject.fromMap(
237+
Map.of("java-increment", (ProxyExecutable) App::javaIncrement)
238+
))
239+
));
240+
...
241+
}
242+
}
243+
}
244+
```
245+
183246
## 4. Building and Testing the Application
184247

185248
Compile and run this Java application with Maven:

0 commit comments

Comments
 (0)