Skip to content

Commit c8c7860

Browse files
authored
manage object lifetime in the face of more aggressive inlining and optimizations (#239)
1 parent e6d8796 commit c8c7860

File tree

1 file changed

+18
-12
lines changed

1 file changed

+18
-12
lines changed

Source/MLX/Cmlx+Util.swift

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ import Foundation
55

66
// return a +1 mlx_vector_array containing the given arrays
77
func new_mlx_vector_array(_ arrays: [MLXArray]) -> mlx_vector_array {
8-
mlx_vector_array_new_data(arrays.map { $0.ctx }, arrays.count)
8+
withExtendedLifetime(arrays) {
9+
mlx_vector_array_new_data(arrays.map { $0.ctx }, arrays.count)
10+
}
911
}
1012

1113
func mlx_vector_array_values(_ vector_array: mlx_vector_array) -> [MLXArray] {
@@ -64,24 +66,28 @@ func mlx_map_string_values(_ mlx_map: mlx_map_string_to_string) -> [String: Stri
6466
}
6567

6668
func new_mlx_array_map(_ dictionary: [String: MLXArray]) -> mlx_map_string_to_array {
67-
let mlx_map = mlx_map_string_to_array_new()
69+
withExtendedLifetime(dictionary) {
70+
let mlx_map = mlx_map_string_to_array_new()
6871

69-
for (key, array) in dictionary {
70-
mlx_map_string_to_array_insert(mlx_map, key.cString(using: .utf8), array.ctx)
71-
}
72+
for (key, array) in dictionary {
73+
mlx_map_string_to_array_insert(mlx_map, key.cString(using: .utf8), array.ctx)
74+
}
7275

73-
return mlx_map
76+
return mlx_map
77+
}
7478
}
7579

7680
func new_mlx_string_map(_ dictionary: [String: String]) -> mlx_map_string_to_string {
77-
let mlx_map = mlx_map_string_to_string_new()
81+
withExtendedLifetime(dictionary) {
82+
let mlx_map = mlx_map_string_to_string_new()
7883

79-
for (key, value) in dictionary {
80-
mlx_map_string_to_string_insert(
81-
mlx_map, key.cString(using: .utf8), value.cString(using: .utf8))
82-
}
84+
for (key, value) in dictionary {
85+
mlx_map_string_to_string_insert(
86+
mlx_map, key.cString(using: .utf8), value.cString(using: .utf8))
87+
}
8388

84-
return mlx_map
89+
return mlx_map
90+
}
8591
}
8692

8793
func new_mlx_closure(_ f: @escaping ([MLXArray]) -> [MLXArray]) -> mlx_closure {

0 commit comments

Comments
 (0)