python - 重新解释 Julia 中的指针

标签 python c++ julia

我有一些具有现有 python 绑定(bind)的 C++ 代码,我正在尝试使用 PyCall 将其移植到 Julia 上。被调用的函数之一会生成一个指向内存中二维数组的指针,我想将 Julia 数组包装到该数组中,以便我可以加/减/乘标量等。我知道数组的大小,并且它当前表示为 PyObject,我可以对其执行 x_ptr[1]x_ptr[2] 并获取正确的值。但我想要一个数组,x

最佳答案

这是一个使用 numpy array interface 的简单示例。默认情况下,PyCall 会将 numpy 数组转换为 Julia 的数组,但我们可以使用 @pycall::Any 注释来阻止这种情况,以显示如何手动执行此操作。您需要深入研究该对象才能找到该指针。

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

当然,我不知道你的python对象是如何存储它的指针的。您必须深入研究 Python 对象才能自己找到该指针。

关于python - 重新解释 Julia 中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47254540/

相关文章:

python - 如何在 urlencoded 字符串中进行字符串替换

python - 下载 Google 电子表格并另存为 xls

C++ 'small' 优化行为异常

julia - 为什么我在 Julia 中的代码随着迭代次数的增加而变慢?

date - 有没有办法在 Julia 中制作自定义日期格式?

python - Django 中的 MySQLdb 错误

python - 安装了 pip,但找不到 virtualenvwrapper_bashrc 在哪里

c++ - 使用 AWS C++ SDK 分段上传 S3

c++ - 将结构推回结构中的 vector

julia - 使用 CuArrays 限制 Julia 中的 GPU 内存