Wrapping a C++ Vector in Rogue
A consequence of a conversation I was having tonight, here's a brief code sample that demonstrates wrapping the C++ vector class in a Rogue class:
VectorWrapper.rogue
#==================================================================
# VectorWrapper.rogue
#
# February 29, 2016 by Abe Pralle
#
# Compile with RogueC v1.0.2+ from
# https://github.com/AbePralle/Rogue
#
# roguec VectorWrapper.rogue --execute
#==================================================================
println "C++ vector wrapping example"
local v = Int32Vector()
v.add( 3 ).add( 4 ).add( 0 )
v[2] = v[0] + v[1]
trace v.count
trace v
nativeHeader
#include <vector>
using namespace std;
endNativeHeader
class Int32Vector : Vector<<Int32,"int">>;
class Vector<<$DataType,$CPPType>>
PROPERTIES
native "vector<" $CPPType ">* vector;"
METHODS
method init
native "$this->vector = new vector<" $CPPType ">();"
method clean_up
println "Deleting vector"
native "delete $this->vector;"
method add( n:Int32 )->this
native "$this->vector->push_back( ("$CPPType") $n );"
return this
method count->Int32
return native( "$this->vector->size()" )->Int32
method get( index:Int32 )->Int32
return native( "$this->vector->operator[]( $index )" )->Int32
method set( index:Int32, value:Int32 )
native "$this->vector->operator[]( $index ) = $value;"
method to->String
local buffer = StringBuilder()
buffer.print( '[' )
local first = true
forEach (n in this)
if (first) first = false
else buffer.print( ',' )
buffer.print( n )
endForEach
buffer.print( ']' )
return buffer->String
endClass
Output
C++ vector wrapping example
v.count:3
v:[3,4,7]
Deleting vector