File tree Expand file tree Collapse file tree
java/com/github/drrb/javarust
rust/com/github/drrb/javarust/lib
test/java/com/github/drrb/javarust Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -107,4 +107,14 @@ interface GreetingSetCallback extends Callback {
107107
108108 void apply (GreetingSet .ByReference greetingSet );
109109 }
110+
111+ /**
112+ * Free the memory used by a Greeting
113+ */
114+ void dropGreeting (Greeting greeting );
115+
116+ /**
117+ * Free the memory used by a GreetingSet
118+ */
119+ void dropGreetingSet (GreetingSet greetingSet );
110120}
Original file line number Diff line number Diff line change @@ -142,6 +142,18 @@ pub extern fn renderGreetings() -> Box<GreetingSet> {
142142 }
143143}
144144
145+ #[ no_mangle]
146+ pub extern fn dropGreeting ( _: Box < Greeting > ) {
147+ // Do nothing here. Because we own it here (we're using a Box) and we're not returning it, Rust
148+ // will assume we don't want it anymore.
149+ }
150+
151+ #[ no_mangle]
152+ pub extern fn dropGreetingSet ( _: Box < GreetingSet > ) {
153+ // Do nothing here. Because we own it here (we're using a Box) and we're not returning it, Rust
154+ // will assume we don't want it anymore.
155+ }
156+
145157/// Convert a native string to a Rust string
146158fn to_string ( pointer : & * const c_char ) -> String {
147159 let slice = unsafe { ffi:: c_str_to_bytes ( pointer) } ;
Original file line number Diff line number Diff line change @@ -68,7 +68,12 @@ public void shouldGetAStructFromRustByValue() {
6868 @ Test
6969 public void shouldGetAStructFromRustByReference () {
7070 Greeting greeting = library .getGreetingByReference ();
71+
7172 assertThat (greeting .text , is ("Hello from Rust!" ));
73+
74+ // Free the memory after using it. We need to do this because JNA assumes
75+ // that the memory is owned by Rust, so Rust must clean it up.
76+ library .dropGreeting (greeting );
7277 }
7378
7479 @ Test
@@ -89,6 +94,7 @@ public void shouldGetListOfStringsFromRustInACallback() {
8994 List <String > greetingStrings = greetings .stream ().map (Greeting ::getText ).collect (toList ());
9095
9196 assertThat (greetingStrings , is (asList ("Hello!" , "Hello again!" )));
97+ greetings .stream ().forEach ((greeting ) -> library .dropGreeting (greeting ));
9298 }
9399
94100 @ Test
@@ -100,5 +106,6 @@ public void shouldGetAStructFromRustContainingAnArrayOfStructs() {
100106 .collect (toList ());
101107
102108 assertThat (greetings , is (asList ("Hello!" , "Hello again!" )));
109+ library .dropGreetingSet (result );
103110 }
104111}
You can’t perform that action at this time.
0 commit comments