@@ -12,6 +12,16 @@ class Source extends Connection
1212 */
1313 public \FFI \CData $ pointer ;
1414
15+ /**
16+ * Pointer to the underlying memory buffer when using
17+ * @see Source::newFromMemory()
18+ *
19+ * Must be freed when no longer needed.
20+ *
21+ * @internal
22+ */
23+ public ?\FFI \CData $ memory = null ;
24+
1525 public function __construct (\FFI \CData $ pointer )
1626 {
1727 $ this ->pointer = FFI ::vips ()->cast (FFI ::ctypes ('VipsSource ' ), $ pointer );
@@ -64,17 +74,27 @@ public static function newFromFile(string $filename): self
6474 */
6575 public static function newFromMemory (string $ data ): self
6676 {
67- # we need to set the memory to a copy of the data that vips_lib
68- # can own and free
77+ # we need to set the memory to a copy of the data
6978 $ n = strlen ($ data );
7079 $ memory = FFI ::vips ()->new ("char[ $ n] " , false , true );
7180 \FFI ::memcpy ($ memory , $ data , $ n );
7281 $ pointer = FFI ::vips ()->vips_source_new_from_memory ($ memory , $ n );
7382
7483 if ($ pointer === null ) {
84+ \FFI ::free ($ memory );
7585 throw new Exception ("can't create source from memory " );
7686 }
7787
78- return new self ($ pointer );
88+ $ source = new self ($ pointer );
89+ $ source ->memory = $ memory ;
90+ return $ source ;
91+ }
92+
93+ public function __destruct ()
94+ {
95+ if ($ this ->memory !== null ) {
96+ \FFI ::free ($ this ->memory );
97+ }
98+ parent ::__destruct ();
7999 }
80100}
0 commit comments