在 Julia 中的函数 ccall 上构造对象

Construct object on function ccall in Julia

我正在尝试简化一些与 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 中这样的事情甚至可能吗?

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

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

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