Skip to content

Instantly share code, notes, and snippets.

@Hywan
Created May 12, 2020 09:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hywan/844142330e0e8cbc13280aa2a0584a57 to your computer and use it in GitHub Desktop.
Save Hywan/844142330e0e8cbc13280aa2a0584a57 to your computer and use it in GitHub Desktop.
Reading WebAssembly memory from Java
import org.wasmer.Instance;
import org.wasmer.Memory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;
class MemoryExample {
public static void main(String[] args) throws IOException {
// Read the WebAssembly bytes.
byte[] bytes = Files.readAllBytes(Paths.get("memory.wasm"));
// Instantiate the WebAssembly module.
Instance instance = new Instance(bytes);
// Get a pointer to the statically allocated string returned by `return_hello`.
Integer pointer = (Integer) instance.exports.getFunction("return_hello").apply()[0];
// Get the exported memory named `memory`.
Memory memory = instance.exports.getMemory("memory");
// Get a direct byte buffer view of the WebAssembly memory.
ByteBuffer memoryBuffer = memory.buffer();
// Prepare the byte array that will hold the data.
byte[] data = new byte[13];
// Let's position the cursor, and…
memoryBuffer.position(pointer);
// … read!
memoryBuffer.get(data);
// Let's encode back to a Java string.
String result = new String(data);
// Hello!
assert result.equals("Hello, World!");
instance.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment