@@ -12,6 +12,16 @@ class Source extends Connection
12
12
*/
13
13
public \FFI \CData $ pointer ;
14
14
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
+
15
25
public function __construct (\FFI \CData $ pointer )
16
26
{
17
27
$ this ->pointer = FFI ::vips ()->cast (FFI ::ctypes ('VipsSource ' ), $ pointer );
@@ -64,17 +74,27 @@ public static function newFromFile(string $filename): self
64
74
*/
65
75
public static function newFromMemory (string $ data ): self
66
76
{
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
69
78
$ n = strlen ($ data );
70
79
$ memory = FFI ::vips ()->new ("char[ $ n] " , false , true );
71
80
\FFI ::memcpy ($ memory , $ data , $ n );
72
81
$ pointer = FFI ::vips ()->vips_source_new_from_memory ($ memory , $ n );
73
82
74
83
if ($ pointer === null ) {
84
+ \FFI ::free ($ memory );
75
85
throw new Exception ("can't create source from memory " );
76
86
}
77
87
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 ();
79
99
}
80
100
}
0 commit comments