[英]Reinterpreting Pointers in Julia
I have some C++ code that has existing python bindings, and I am trying to graft it on to Julia using PyCall.我有一些具有现有 python 绑定的 C++ 代码,我正在尝试使用 PyCall 将它移植到 Julia。 One of the functions that gets called generates a pointer to a 2D array in memory to which I would like to wrap a Julia array around so that I can add/subtract/multiply by scalars, etc. I know the size of the array, and it's currently represented as a PyObject to which I can do
x_ptr[1]
, x_ptr[2]
and get correct values out.被调用的函数之一在内存中生成一个指向二维数组的指针,我想将 Julia 数组包装到该数组中,以便我可以添加/减去/乘以标量等。我知道数组的大小,并且它目前表示为一个 PyObject,我可以对其执行
x_ptr[1]
、 x_ptr[2]
并获得正确的值。 But I'd like to have an array, x
.但我想要一个数组
x
。
Here's a simple example using numpy array interface .这是一个使用 numpy array interface的简单示例。 By default, PyCall converts numpy arrays to Julia's arrays, but we can prevent that with
@pycall
and the ::Any
annotation to show how you'd do it manually.默认情况下,PyCall 将 numpy 数组转换为 Julia 的数组,但我们可以使用
@pycall
和::Any
注释来防止这种情况@pycall
,以显示您如何手动执行此操作。 You need to dig into the object to find that pointer.您需要深入研究对象以找到该指针。
julia> obj = @pycall numpy.reshape(numpy.arange(20), (4,5))::Any
PyObject array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
julia> array_interface = obj.__array_interface__
Dict{Any,Any} with 6 entries:
"shape" => (4, 5)
"strides" => nothing
"typestr" => "<i8"
"data" => (4705395216, false)
"descr" => Tuple{String,String}[("", "<i8")]
"version" => 3
julia> array_interface["data"] # This is the actual pointer!
(4705395216, false)
julia> unsafe_wrap(Matrix{Int}, Ptr{Int}(array_interface["data"][1]), reverse(array_interface["shape"]))
5×4 Array{Int64,2}:
0 5 10 15
1 6 11 16
2 7 12 17
3 8 13 18
4 9 14 19
Of course, I don't know how your python object stores its pointer.当然,我不知道你的python 对象是如何存储它的指针的。 You'll have to dig into your Python object to find that pointer yourself.
您必须深入研究 Python 对象才能自己找到该指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.