【问题标题】:Construct object on function ccall in Julia在Julia中的函数调用上构造对象
【发布时间】:2020-07-14 22:13:43
【问题描述】:

我正在尝试简化与 C 的某些绑定,但我不确定这是否可能,我正在尝试做的是传递一个数组并期望在一个函数中接收,以便可以通过指定的类型构造一个对象在参数中或通过 ccall 调用正确的转换函数并初始化一个结构对象。

之前的代码,绑定的都是Vector3(v...)Color(c...),有没有办法避免这种自动处理?

drawline(startPos, endPos, color) = ccall((:DrawLine3D, "my_lib"), Cvoid, (Vector3,Vector3,Color), Vector3(startPos...), Vector3(endPos...), Color(color...))
drawpoint([10,10,10],[100,100,100],[155,155,155,255]) # call example

是否可以通过这样的方式减少代码?:

struct Vector3
    x::Cfloat
    y::Cfloat
    z::Cfloat
    Vector3((x,y,z))=new(x,y,z)
end
#first attempt
#trying to call the Vector3 constructor without calling explicitly
drawpoint(startpos::Vector3,endpos::Vector3,color::Color) = ccall((:DrawPoint3D, "my_lib"), Cvoid, (Vector3,Vector3,Color), startpos,endpos,color) 

#second attempt (should be the simplest way to go)
#trying to receive arrays so ccall can convert from list or tuple to Struct object
drawpoint(startpos,endpos,color) = ccall((:DrawPoint3D, "my_lib"), Cvoid, (Vector3,Vector3,Color), startpos,endpos,color) 

这样的事情在 Julia 中是否可行?

【问题讨论】:

    标签: constructor type-conversion julia implicit-conversion


    【解决方案1】:

    您只需要定义适当的conversionccall 会为你打电话。我认为应该这样做:

    Base.convert(::Type{Vector3}, x::AbstractVector) = Vector3(x)
    

    您可能想要添加一些长度检查等,为了提高效率,我可能建议使用元组或StaticArrays 而不是Vectors。

    【讨论】:

    • 我明白了,非常感谢,我读过一些关于它的东西,但不认为这是这样做的方法,这样的例子在 C 接口文档中会很棒,这大大改进了我的代码。
    猜你喜欢
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多