diff --git a/c_glib/arrow-glib/basic-array.cpp b/c_glib/arrow-glib/basic-array.cpp index b051c97b54657..db0466017990f 100644 --- a/c_glib/arrow-glib/basic-array.cpp +++ b/c_glib/arrow-glib/basic-array.cpp @@ -516,6 +516,34 @@ garrow_array_to_string(GArrowArray *array, GError **error) } } +/** + * garrow_array_view: + * @array: A #GArrowArray. + * @return_type: A #GArrowDataType of the returned view. + * @error: (nullable): Return location for a #GError or %NULL. + * + * Returns: (nullable) (transfer full): A zero-copy view of this array + * with the given type. This method checks if the `return_type` are + * layout-compatible. + * + * Since: 0.15.0 + */ +GArrowArray * +garrow_array_view(GArrowArray *array, + GArrowDataType *return_type, + GError **error) +{ + auto arrow_array_raw = garrow_array_get_raw(array); + auto arrow_return_type = garrow_data_type_get_raw(return_type); + std::shared_ptr arrow_array; + auto status = arrow_array_raw->View(arrow_return_type, &arrow_array); + if (garrow_error_check(error, status, "[array][view]")) { + return garrow_array_new_raw(&arrow_array); + } else { + return NULL; + } +} + G_DEFINE_TYPE(GArrowNullArray, garrow_null_array, diff --git a/c_glib/arrow-glib/basic-array.h b/c_glib/arrow-glib/basic-array.h index d10abea3e03c7..cb508593a7ac5 100644 --- a/c_glib/arrow-glib/basic-array.h +++ b/c_glib/arrow-glib/basic-array.h @@ -60,6 +60,10 @@ GArrowArray *garrow_array_slice (GArrowArray *array, gint64 length); gchar *garrow_array_to_string (GArrowArray *array, GError **error); +GARROW_AVAILABLE_IN_0_15 +GArrowArray *garrow_array_view(GArrowArray *array, + GArrowDataType *return_type, + GError **error); #define GARROW_TYPE_NULL_ARRAY (garrow_null_array_get_type()) diff --git a/c_glib/test/test-array.rb b/c_glib/test/test-array.rb index 3befde3c7a9bb..7ca34c55d37e5 100644 --- a/c_glib/test/test-array.rb +++ b/c_glib/test/test-array.rb @@ -115,4 +115,19 @@ def test_to_s ] CONTENT end + + sub_test_case("#view") do + def test_valid + assert_equal(build_float_array([0.0, 1.5, -2.5, nil]), + build_int32_array([0, 1069547520, -1071644672, nil]).view(Arrow::FloatDataType.new)) + end + + def test_invalid + message = "[array][view]: Invalid: " + + "Can't view array of type int16 as int8: incompatible layouts" + assert_raise(Arrow::Error::Invalid.new(message)) do + build_int16_array([0, -1, 3]).view(Arrow::Int8DataType.new) + end + end + end end