我需要在 Julia 的可调用函数 determine_string(...) 中分配内存,请参见下面的代码:
#!/usr/bin/env julia
module ProductionCode
import Printf
Base.@ccallable function determine_string(msg_p_p::Ptr{Ptr{Cchar}})::Nothing
println("determine_string(): msg_p_p ", msg_p_p)
json_string::String = join([Printf.@sprintf("%15.7f", rand()) for i in 1:10])
size_for_malloc::Csize_t = 1 + length(json_string)
msg_p_p = @ccall malloc(size_for_malloc::Csize_t)::Ptr{Nothing}
println("determine_string(): msg_p_p ", msg_p_p)
println("determine_string(): json_string ", json_string)
@ccall memcpy(msg_p_p::Ptr{Ptr{Cchar}}, json_string::Ptr{Cchar}, size_for_malloc::Csize_t)::Cvoid
return nothing
end
end # ProductionCode
function test()::Nothing
msg_p::Ptr{Cchar} = C_NULL
msg_p_p = <pointer to msg_p>
println("test(): msg_p ", msg_p)
ProductionCode.determine_string(msg_p_p)
println("test(): msg_p ", msg_p)
@ccall printf("printf: %s\n"::Ptr{Cchar}, msg_p::Ptr{Cchar})::Cint
julia_string::String = Base.unsafe_string(Base.convert(Ptr{Cchar}, msg_p))
@ccall free(msg_p::Ptr{Cchar})::Cvoid
msg_p = C_NULL
return nothing
end
test()
这里 determine_string(...) 表示一个函数,它确定必须发送给 C 中的调用者的可变长度字符串。调用者将使用该字符串并释放内存。出于单元测试的目的,determine_string(...) 也必须可以从 Julia 调用。
问题: