Skip to content

Commit f8110be

Browse files
committed
Use a global empty array in callback
1 parent 4b2cbc3 commit f8110be

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

src/NLopt.jl

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -453,14 +453,21 @@ srand_time() = nlopt_srand_time()
453453
############################################################################
454454
# Objective function:
455455

456+
const _empty_vector = Cdouble[]
457+
458+
@inline function _get_empty_vector()
459+
@assert isempty(_empty_vector) "Builtin empty vector modified by user"
460+
return _empty_vector
461+
end
462+
456463
function nlopt_callback_wrapper(
457464
n::Cuint,
458465
p_x::Ptr{Cdouble},
459466
p_grad::Ptr{Cdouble},
460467
d::Callback_Data,
461468
)::Cdouble
462469
x = unsafe_wrap(Array, p_x, (n,))
463-
grad = p_grad == C_NULL ? Cdouble[] : unsafe_wrap(Array, p_grad, (n,))
470+
grad = p_grad == C_NULL ? _get_empty_vector() : unsafe_wrap(Array, p_grad, (n,))
464471
try
465472
return d.f(x, grad)
466473
catch e
@@ -526,6 +533,8 @@ end
526533
############################################################################
527534
# Vector-valued constraints
528535

536+
const _empty_matrix = zeros(Cdouble, 0, 0)
537+
529538
function nlopt_vcallback_wrapper(
530539
m::Cuint,
531540
p_res::Ptr{Cdouble},
@@ -537,7 +546,7 @@ function nlopt_vcallback_wrapper(
537546
res = unsafe_wrap(Array, p_res, (m,))
538547
x = unsafe_wrap(Array, p_x, (n,))
539548
grad =
540-
p_grad == C_NULL ? zeros(Cdouble, 0, 0) :
549+
p_grad == C_NULL ? _empty_matrix :
541550
unsafe_wrap(Array, p_grad, (n, m))
542551
try
543552
d.f(res, x, grad)

0 commit comments

Comments
 (0)