簡體   English   中英

將變量轉換為 Julia 中的 void 指針

[英]Cast a variable to void pointer in Julia

在 C/C++ 中,我們可以這樣做:

double my_var = 4.32;
void* my_var_ptr = &my_var;

這導致my_var_ptr成為一個空指針,指向存儲值4.32的 memory。

我試圖在 Julia 中做同樣的事情,但我遇到了幾個錯誤。 天真地,我試過這個:

my_var=Cdouble(4.32)
my_var_ptr=Ptr{Cvoid}(pointer(my_var))

失敗並出現錯誤: ERROR: MethodError: no method matching pointer(::Float64)失敗(我假設)是因為我試圖從Cdouble object 創建Cvoid指針。

有什么解決辦法嗎?

提前致謝!

TL; DR

julia> my_var = Cdouble(4.32)
julia> my_var_ptr = Ptr{Cvoid}(pointer_from_objref(Ref(my_var)))
Ptr{Nothing} @0x00007f2a9148c6c0

pointer僅適用於類似數組的元素

julia> methods(pointer)
# 18 methods for generic function "pointer":
[1] pointer(a::Random.UnsafeView) in Random at /usr/share/julia/stdlib/v1.7/Random/src/RNGs.jl:516
[2] pointer(x::SuiteSparse.CHOLMOD.Sparse{Tv}) where Tv in SuiteSparse.CHOLMOD at /usr/share/julia/stdlib/v1.7/SuiteSparse/src/cholmod.jl:359
[3] pointer(x::SuiteSparse.CHOLMOD.Dense{Tv}) where Tv in SuiteSparse.CHOLMOD at /usr/share/julia/stdlib/v1.7/SuiteSparse/src/cholmod.jl:358
[4] pointer(x::SuiteSparse.CHOLMOD.Factor{Tv}) where Tv in SuiteSparse.CHOLMOD at /usr/share/julia/stdlib/v1.7/SuiteSparse/src/cholmod.jl:360
[5] pointer(V::SubArray{T, N, P, I, true} where {T, N, P, I<:Union{Tuple{Vararg{Real}}, Tuple{AbstractUnitRange, Vararg{Any}}}}, i::Int64) in Base at subarray.jl:431
[6] pointer(V::SubArray{T, N, P, I, true} where {T, N, P, I}, i::Int64) in Base at subarray.jl:430
[7] pointer(V::SubArray{<:Any, <:Any, <:Array, <:Tuple{Vararg{Union{Int64, AbstractRange{Int64}}}}}, is::Base.AbstractCartesianIndex{N}) where N in Base at subarray.jl:433
[8] pointer(V::SubArray{<:Any, <:Any, <:Array, <:Tuple{Vararg{Union{Int64, AbstractRange{Int64}}}}}, is::Tuple) in Base at deprecated.jl:212
[9] pointer(A::PermutedDimsArray, i::Integer) in Base.PermutedDimsArrays at permuteddimsarray.jl:61
[10] pointer(x::AbstractArray{T}) where T in Base at abstractarray.jl:1164
[11] pointer(x::AbstractArray{T}, i::Integer) where T in Base at abstractarray.jl:1165
[12] pointer(p::Cstring) in Base at c.jl:186
[13] pointer(buffer::Base64.Buffer) in Base64 at /usr/share/julia/stdlib/v1.7/Base64/src/buffer.jl:20
[14] pointer(x::SubString{String}) in Base at strings/substring.jl:122
[15] pointer(x::SubString{String}, i::Integer) in Base at strings/substring.jl:123
[16] pointer(p::Cwstring) in Base at c.jl:187
[17] pointer(s::String) in Base at strings/string.jl:95
[18] pointer(s::String, i::Integer) in Base at strings/string.jl:96

但是,您應該檢查pointer_from_objref ,例如:

julia> pointer_from_objref(Ref(1))
Ptr{Nothing} @0x00007f2a914feb60

但是從維基...

獲取Julia object的memory地址作為Ptr。 結果 Ptr 的存在不會保護 object 免受垃圾收集,因此您必須確保 object 在 Ptr 將被使用的整個過程中保持引用。

這個 function 可能不會在不可變對象上調用,因為它們沒有穩定的 memory 地址。

另見unsafe_pointer_from_objref

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM