# HG changeset patch # User Doug Simon # Date 1391708565 -3600 # Node ID 4fa77c58ad8f37689db77091245735f5bf500482 # Parent 1398243a0efa20413b072abafb7c3b6ccc2fa6d1 added utility methods for writing a Java string to a native memory buffer as a C string diff -r 1398243a0efa -r 4fa77c58ad8f graal/com.oracle.graal.graph/src/com/oracle/graal/graph/UnsafeAccess.java --- a/graal/com.oracle.graal.graph/src/com/oracle/graal/graph/UnsafeAccess.java Thu Feb 06 18:41:16 2014 +0100 +++ b/graal/com.oracle.graal.graph/src/com/oracle/graal/graph/UnsafeAccess.java Thu Feb 06 18:42:45 2014 +0100 @@ -49,4 +49,33 @@ throw new RuntimeException("exception while trying to get Unsafe.theUnsafe via reflection:", e); } } + + /** + * Copies the contents of a {@link String} to a native memory buffer as a {@code '\0'} + * terminated C string. The native memory buffer is allocated via + * {@link Unsafe#allocateMemory(long)}. The caller is responsible for releasing the buffer when + * it is no longer needed via {@link Unsafe#freeMemory(long)}. + * + * @return the native memory pointer of the C string created from {@code s} + */ + public static long createCString(String s) { + return writeCString(s, unsafe.allocateMemory(s.length() + 1)); + } + + /** + * Writes the contents of a {@link String} to a native memory buffer as a {@code '\0'} + * terminated C string. The caller is responsible for ensuring the buffer is at least + * {@code s.length() + 1} bytes long. The caller is also responsible for releasing the buffer + * when it is no longer. + * + * @return the value of {@code buf} + */ + public static long writeCString(String s, long buf) { + int size = s.length(); + for (int i = 0; i < size; i++) { + unsafe.putByte(buf + i, (byte) s.charAt(i)); + } + unsafe.putByte(buf + size, (byte) '\0'); + return buf; + } }