简体   繁体   中英

Writing an iterator for a CxxWrap vector

I'm evaluating CxxWrap for a Julia (1.x) project I'm working on. I'm interested in having my CxxWrap code return a std::vector of a type, and iterating over the vector in my Julia code. The c++ part looks something like this:

using PointVec = std::vector<Point2D>;
.
.
.
JLCXX_MODULE define_julia_module(jlcxx::Module& types) {
.
.
.
    types.add_type<PointVec>("PointVec")
      .method("length", &PointVec::size)
      .method("getindex", [](const PointVec& vec, size_t index) {
                        return vec.at(index);
                    });
.
.
.
}

This is based on some searching I've already done. The example that I cribbed from alluded to creating an iterator on the Julia side, but didn't elaborate. The descriptions I've seen of creating Julia iterators are pretty daunting, and it's not at all obvious how to plumb in the CxxWrap type that I'm importing. Any tips would be appreciated.

With a lot of help from Jan Strube on the Julia Discourse site, I came up with an approach that works:

module BoostWrapper
using CxxWrap
@wrapmodule("libboost_wrap")
function __init__()
    @initcxx
end
export Point2D, PointVec, getx, gety,
    Polygon2D, PolygonVec, add_vertex, scale_polygon, get_vertices,
    poly_intersection, intersection_point
end
using Main.BoostWrapper

import Base: getindex, length, convert, iterate, size

iterate(it::PointVec) = length(it) > 0 ? (it[1], 2) : nothing
iterate(it::PointVec, i) = i <= length(it) ? (it[i], i+1) : nothing
length(it::PointVec) = Main.BoostWrapper.size(it)
getindex(it::PointVec, i) = Main.BoostWrapper.at(it, convert(UInt64, i - 1))

eltype(::Type{PointVec}) = Point2D

p1 = Point2D(-10.0, 10.0)
p2 = Point2D(10.0, 10.0)
p3 = Point2D(10.0, -10.0)
p4 = Point2D(-10.0, -10.0)
obstacle = Polygon2D()
add_vertex(obstacle, p1)
add_vertex(obstacle, p2)
add_vertex(obstacle, p3)
add_vertex(obstacle, p4)

pts = get_vertices(obstacle)

for pt in pts
    println("current pt: ", getx(pt), ", ", gety(pt))
end

I'm including a lot of detail, because it turned out there were subtleties involved in name resolution, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM