Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AbstractArray -> MallocArray conversion? #44

Open
jonniediegelman opened this issue Apr 24, 2023 · 3 comments
Open

AbstractArray -> MallocArray conversion? #44

jonniediegelman opened this issue Apr 24, 2023 · 3 comments

Comments

@jonniediegelman
Copy link

I find MallocArray useful for working with ccall because it allows me to more easily pass in ref-wrapped structs that contain arrays. But it's a little clunky to manually have to convert from a plain Array to a MallocArray. Would there be anything wrong with having a default conversion like this?

function Base.convert(::Type{MallocArray{T, N}}, x::AbstractArray{T, N}) where {T, N}
    return MallocArray(pointer(x), length(x), size(x))
end
@brenhinkeller
Copy link
Owner

Ah, so the trouble there is that MallocArray's are expecting to be given a pointer to memory that has been manually allocated with malloc. This could technically still work if for Arrays (or more generally DenseArrays -- but not all AbstractArrays) if you could guarantee that the memory backing the Array would not be garbage collected by Julia in the meanwhile, and that you wouldn't ever attempt to free the resulting MallocArray.

If you can guarantee for your use case that Julia won't GC the underlying memory and wanted to implement a method like this, I'd accept a PR -- but it should probably convert to StaticTools.ArrayView (which also just has fields of pointer, length, and size) rather than StaticTools.MallocArray to ensure the resulting object can't be accidentally freed (because that would be bad).

In the meanwhile, we do also have this method (which works on any AbstractArray and just copies the data to a new MallocArray):

julia> a = collect(1:5)
5-element Vector{Int64}:
 1
 2
 3
 4
 5

julia> MallocArray(a)
5-element MallocVector{Int64}:
 1
 2
 3
 4
 5

@jonniediegelman
Copy link
Author

Okay, thanks! I didn't know about ArrayView, it seems like that's what I actually want here.

@brenhinkeller
Copy link
Owner

Cool! PRs welcome if you want to change anything here!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants