【问题标题】:C struct type correspondences in JuliaJulia 中的 C 结构类型对应关系
【发布时间】:2018-11-27 18:13:59
【问题描述】:

我尝试在 Julia 中使用带有结构作为参数的 C 函数,我调用了函数,但出现了问题。一个简单的例子如下:

在 C 中:

typedef struct {
    int width;
    int height;
    int stride;
    float* elements;
} Matriz;

是一个存储矩阵的简单结构,具有widthheigthstrideelements 字段

float GetElm(const Matriz A, int row, int col)
{
    return (row < A.height && col < A.width ?
        A.elements[row * A.stride + col] : 0);
}

是一个函数,它返回给定行和列的矩阵元素。

在 Julia 中:

immutable Matriz
width::Cint
height::Cint
stride::Cint
elements::Array{Float32,1}
end

M=Matriz(5,5,5,Array{Float32,1}(collect(0:24))) #creating a Matrix of 5x5


ccall((:GetElm,"path/to/dll"),Float32,(Matriz,Cint,Cint),M,0,1)

ccall 根据代码应该返回1.0,但是返回另一个值,是不是我做错了什么?

【问题讨论】:

    标签: c struct julia


    【解决方案1】:

    当您直接使用数组参数对 ccall 进行函数调用时,Julia 会发送 Array 的本机地址。

    但是,对于structs,该过程不是自动的。仍然可以发送数组的本机地址的一种方法是使用pointer。如果您要使用此方法,则需要在 Julia 中更新您的 struct

    struct Matriz
        width::Cint
        height::Cint
        stride::Cint
        elements::Ptr{Cfloat}
    end
    
    arr = Array{Float32,1}(collect(0:24))
    M=Matriz(5,5,5, pointer(arr)) #creating a Matrix of 5x5
    ccall((:GetElm,"mylib.so"),Float32,(Matriz,Cint,Cint),M,0,1)
    

    在这样做之前,请阅读pointer 的手册,因为由于 Julia GC,这是一个不安全的操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-19
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      相关资源
      最近更新 更多