diff --git a/src/main/java/jnr/ffi/Struct.java b/src/main/java/jnr/ffi/Struct.java index 2f134796..c07f93b7 100755 --- a/src/main/java/jnr/ffi/Struct.java +++ b/src/main/java/jnr/ffi/Struct.java @@ -2469,8 +2469,9 @@ public final java.lang.String get() { public final void set(java.lang.String value) { if (value != null) { - valueHolder = getRuntime().getMemoryManager().allocateDirect(value.length() * 4); - valueHolder.putString(0, value, value.length() * 4, charset); + int maxBytes = (value.length() * 4) + 1; // Additional byte required for trailing null termination. + valueHolder = getRuntime().getMemoryManager().allocateDirect(maxBytes); + valueHolder.putString(0, value, maxBytes, charset); getMemory().putPointer(offset(), valueHolder); } else { diff --git a/src/test/java/jnr/ffi/struct/AsciiStringFieldTest.java b/src/test/java/jnr/ffi/struct/AsciiStringFieldTest.java index f2d0fce1..c316306a 100644 --- a/src/test/java/jnr/ffi/struct/AsciiStringFieldTest.java +++ b/src/test/java/jnr/ffi/struct/AsciiStringFieldTest.java @@ -101,4 +101,24 @@ public StructWithStringByRef() { assertEquals(testValue, struct.stringValue.get()); } + + public static final class StructWithConsecutiveStringsByRef extends Struct { + private final AsciiStringRef firstValue = new AsciiStringRef(); + private final AsciiStringRef secondValue = new AsciiStringRef(); + + public StructWithConsecutiveStringsByRef() { + super(runtime); + } + } + + @Test public void testStructWithConsecutiveStringsByRef() { + final String testValue = "some test string"; + final StructWithConsecutiveStringsByRef struct = new StructWithConsecutiveStringsByRef(); + + struct.firstValue.set(""); + struct.secondValue.set(testValue); + + assertEquals("", struct.firstValue.get()); + assertEquals(testValue, struct.secondValue.get()); + } } diff --git a/src/test/java/jnr/ffi/struct/UTF8StringFieldTest.java b/src/test/java/jnr/ffi/struct/UTF8StringFieldTest.java index 20303eac..32e8840f 100644 --- a/src/test/java/jnr/ffi/struct/UTF8StringFieldTest.java +++ b/src/test/java/jnr/ffi/struct/UTF8StringFieldTest.java @@ -122,4 +122,24 @@ public StructWithStringByRef() { assertEquals(testValue, struct.stringValue.get()); } + + public static final class StructWithConsecutiveStringsByRef extends Struct { + private final UTF8StringRef firstValue = new UTF8StringRef(); + private final UTF8StringRef secondValue = new UTF8StringRef(); + + public StructWithConsecutiveStringsByRef() { + super(runtime); + } + } + + @Test public void testStructWithConsecutiveStringsByRef() { + final String testValue = "some test string"; + final StructWithConsecutiveStringsByRef struct = new StructWithConsecutiveStringsByRef(); + + struct.firstValue.set(""); + struct.secondValue.set(testValue); + + assertEquals("", struct.firstValue.get()); + assertEquals(testValue, struct.secondValue.get()); + } }