You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: graalwasm/graalwasm-embed-c-code-guide/README.md
+63Lines changed: 63 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -180,6 +180,69 @@ public class App {
180
180
}
181
181
```
182
182
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
+
externintjavaInc(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
+
voidfloyd(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.
0 commit comments