diff --git a/doc/source/user/migration_guide.rst b/doc/source/user/migration_guide.rst index 6e432e307530..7a76f71ac9d7 100644 --- a/doc/source/user/migration_guide.rst +++ b/doc/source/user/migration_guide.rst @@ -57,6 +57,20 @@ From GDAL 3.13 to GDAL 3.14 ``gdal.DontUseExceptions()`` mode now also sets ``gdal.OF_VERBOSE_ERROR`` automatically, unless the new ``gdal.OF_SILENT_ERROR`` flag is set. +- Changes impacting C# users: + + * Several call sites have been removed from from the C# bindings due to corrected and improved type mapping + + + The overloads of ``OSGeo.GDAL.Group.CreateAttribute``, ``OSGeo.GDAL.MDArray.CreateAttribute``, and ``OSGeo.GDAL.MDArray.Resize`` which accepted ``uint[]`` are no longer available due to that parameter being incorrectly type mapped to ``uint[]`` instead of ``ulong[]``. + + + The overload of ``OSGeo.GDAL.Transformer.TransformPoints`` which has parameter ``double[] panSuccess`` has been removed due to that parameter being incorrectly type mapped to ``double[]`` instead of ``int[]``. + + + ``Gdal.GCPsToHomography(int nGCPs, IntPtr pGCPs, double[] argout)`` has been removed due to the difficulty of requiring users to marshal their own ``GCP`` value arrays. It has been replaced with ``GCPsToHomography(GCP[] nGCPs, double[] argout)``. + + + ``Gdal.wrapper_GDALBuildVRT_objects`` and ``Gdal.wrapper_GDALMultiDimTranslateDestName`` have been removed due to the difficulty of requiring users to marshal their own `Dataset` reference arrays. They have been replaced with ``Dataset.BuildVRT`` and ``Dataset.MultiDimTranslate``, respectively. + + + The ``OSGeo.GDAL.MDArray.BuildOverviews`` method previously accepted a ``SWIGTYPE_p_int`` parameter argument but now takes an ``int[]``. + From GDAL 3.12 to GDAL 3.13 --------------------------- diff --git a/swig/csharp/CMakeLists.txt b/swig/csharp/CMakeLists.txt index dc7cff6db2ab..a4b2fa9dc7b5 100644 --- a/swig/csharp/CMakeLists.txt +++ b/swig/csharp/CMakeLists.txt @@ -506,6 +506,14 @@ if (CSHARP_BUILD_SAMPLES) SYSTEM_DEPENDS OSGeo.GDAL) + gdal_build_csharp_sample( + OUTPUT GDALFieldValues.exe + SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/apps/GDALFieldValues.cs + DEPENDS + gdal_csharp + SYSTEM_DEPENDS + OSGeo.GDAL) + gdal_build_csharp_sample( OUTPUT GDALDatasetWrite.exe SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/apps/GDALDatasetWrite.cs @@ -661,6 +669,7 @@ if (CSHARP_BUILD_SAMPLES) OSGeo.GDAL.Samples.GDALAdjustContrast OSGeo.GDAL.Samples.GDALDatasetRasterIO OSGeo.GDAL.Samples.GDALWrite + OSGeo.GDAL.Samples.GDALFieldValues OSGeo.GDAL.Samples.GDALDatasetWrite OSGeo.GDAL.Samples.GDALColorTable OSGeo.GDAL.Samples.WKT2WKB @@ -707,6 +716,11 @@ if (CSHARP_RUN_TESTS) COMMAND ${CMAKE_CURRENT_BINARY_DIR}/GDALWrite/GDALWrite Data/sample.tif) set_property(TEST csharp_gdalwrite PROPERTY ENVIRONMENT "${TEST_ENV}") set_property(TEST csharp_gdalwrite PROPERTY DEPENDS csharp_createdata) + add_test( + NAME csharp_gdalfieldvalues + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + COMMAND ${CMAKE_CURRENT_BINARY_DIR}/GDALFieldValues/GDALFieldValues) + set_property(TEST csharp_gdalfieldvalues PROPERTY ENVIRONMENT "${TEST_ENV}") add_test( NAME csharp_gdaldatasetwrite WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} diff --git a/swig/csharp/apps/GDALDatasetRasterIOEx.cs b/swig/csharp/apps/GDALDatasetRasterIOEx.cs index ff9c7e82d4a0..c76172eb6a83 100644 --- a/swig/csharp/apps/GDALDatasetRasterIOEx.cs +++ b/swig/csharp/apps/GDALDatasetRasterIOEx.cs @@ -46,16 +46,15 @@ public static void usage() System.Environment.Exit(-1); } - public static int ProgressFunc(double Complete, IntPtr Message, IntPtr Data) + public static bool ProgressFunc(double Complete, string Message, TestData Data) { - Console.Write("Processing ... " + Complete * 100 + "% Completed."); - if (Message != IntPtr.Zero) - Console.Write(" Message:" + System.Runtime.InteropServices.Marshal.PtrToStringAnsi(Message)); - if (Data != IntPtr.Zero) - Console.Write(" Data:" + System.Runtime.InteropServices.Marshal.PtrToStringUni(Data)); + Console.Write("\e[G\e[KProcessing ... " + Complete * 100 + "% Completed."); + if (Message != null) + Console.Write(" Message:" + Message); + if (Data != null) + Console.Write(" Data1:" + Data.Text1 + " Data2:" + Data.Text2); - Console.WriteLine(""); - return 1; + return true; } private static RIOResampleAlg resampleAlg = RIOResampleAlg.GRIORA_NearestNeighbour; @@ -291,21 +290,12 @@ private static void SaveBitmapDirect(string filename, Dataset ds, int xOff, int using (RasterIOExtraArg arg = new RasterIOExtraArg()) { - GCHandle handle = GCHandle.Alloc("Test data", GCHandleType.Pinned); - try - { - arg.nVersion = argVersion; - arg.eResampleAlg = resampleAlg; - arg.pfnProgress = new Gdal.GDALProgressFuncDelegate(ProgressFunc); - arg.pProgressData = handle.AddrOfPinnedObject(); // or IntPtr.Zero if not data to be added; - arg.bFloatingPointWindowValidity = 0; - ds.ReadRaster(xOff, yOff, width, height, buf, imageWidth, imageHeight, dataType, - channelCount, bandMap, pixelSpace, stride, 1, arg); - } - finally - { - handle.Free(); - } + arg.nVersion = argVersion; + arg.eResampleAlg = resampleAlg; + arg.SetProgressDelegate(ProgressFunc, new TestData("First Message", "Second Message")); + arg.bFloatingPointWindowValidity = 0; + ds.ReadRaster(xOff, yOff, width, height, buf, imageWidth, imageHeight, dataType, + channelCount, bandMap, pixelSpace, stride, 1, arg); } } finally @@ -314,6 +304,8 @@ private static void SaveBitmapDirect(string filename, Dataset ds, int xOff, int } bitmap.Save(filename); - ct.Dispose(); + ct?.Dispose(); } } + +record TestData(string Text1, string Text2); diff --git a/swig/csharp/apps/GDALDatasetWrite.cs b/swig/csharp/apps/GDALDatasetWrite.cs index 27e95f795083..a93a4c9d219f 100644 --- a/swig/csharp/apps/GDALDatasetWrite.cs +++ b/swig/csharp/apps/GDALDatasetWrite.cs @@ -14,6 +14,7 @@ *****************************************************************************/ using System; +using System.Linq; using System.Globalization; using OSGeo.GDAL; @@ -94,21 +95,54 @@ public static void Main(string[] args) byte[] buffers = new byte[w * h * 3]; - for (int i = 0; i < w; i++) + for (int y = 0; y < h; y++) { - for (int j = 0; j < h; j++) + for (int x = 0; x < w; x++) { - buffers[(i * w + j)] = (byte)(256 - i * 256 / w); - buffers[w * h + (i * w + j)] = 0; - buffers[2 * w * h + (i * w + j)] = (byte)(i * 256 / w); + //red + buffers[(y * w + x)] = ToByte(256 * x * (h - y) / (w * h)); + //green + buffers[w * h + (y * w + x)] = ToByte(256 - 256 * (w - x) * y / (w * h)); + //blue + buffers[2 * w * h + (y * w + x)] = ToByte(Random.Shared.Next(0, 256)); } } - int[] iBandMap = { 1, 2, 3 }; - ds.WriteRaster(0, 0, w, h, buffers, w, h, 3, iBandMap, 0, 0, 0); - + ds.WriteRaster(0, 0, w, h, buffers, w, h, 3); ds.FlushCache(); + + for (int i = 1; i <= ds.RasterCount; i++) + { + using var band = ds.GetRasterBand(i); + Console.WriteLine($"Band {i} Histogram (0 -> 255)"); + Console.WriteLine($"================================"); + DrawHistogram(band); + Console.WriteLine(); + } + } + } + } + + private static byte ToByte(double value, int min = byte.MinValue, int max = byte.MaxValue) + => value < min ? (byte)min : value > max ? (byte)max : (byte)value; + + private static void DrawHistogram(Band band) + { + const int height = 22; + const int width = 32; + const char block = '█'; + int[] histogram = new int[width]; + band.GetHistogram(histogram: histogram, approx_ok: false); + + double value = histogram.Max(); + double vStep = value / height; + for (int y = 0; y < height; y++, value -= vStep) + { + for (int x = 0; x < histogram.Length; x++) + { + Console.Write(histogram[x] >= value ? block : ' '); } + Console.WriteLine(); } } } diff --git a/swig/csharp/apps/GDALFieldValues.cs b/swig/csharp/apps/GDALFieldValues.cs new file mode 100644 index 000000000000..25e272e95aad --- /dev/null +++ b/swig/csharp/apps/GDALFieldValues.cs @@ -0,0 +1,210 @@ +/****************************************************************************** + * + * Name: GDALFieldValues.cs + * Project: GDAL CSharp Interface + * Purpose: A sample app to demonstrate getting and setting field values of + * different types of field values. + * Author: Michael Bucari-Tovo, mbucari1@gmail.com + * + ****************************************************************************** + * Copyright (c) 2026, Michael Bucari-Tovo + * + * SPDX-License-Identifier: MIT + *****************************************************************************/ + +using OSGeo.GDAL; +using OSGeo.OGR; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Threading.Tasks; + +namespace TestGdalCSharp; + +public static class GDALVector +{ + const string UnicodeString = "Ĥĕļĺō Ŵŏŕľď"; + + public static async Task Main() + { + Console.OutputEncoding = System.Text.Encoding.UTF8; + Gdal.AllRegister(); + using var reg = Gdal.GetGlobalAlgorithmRegistry(); + + Console.WriteLine("Listing all algorithms and their sub-algorithms with parameters:"); + foreach (var alg in reg.Algorithms()) + { + Console.WriteLine($" Algorithm: {alg.GetName()}"); + foreach (var subAlg in alg.SubAlgorithms()) + { + Console.WriteLine($" SubAlgorithm: {subAlg.GetName()}"); + foreach (var arg in subAlg.Args().OfListType(true)) + { + Console.WriteLine($" Parameter: {arg.GetName()}, Type: {Gdal.AlgorithmArgTypeName(arg.GetType_())}"); + } + } + } + + TestAlgorithmArgsIntegerList(reg); + TestAlgorithmArgsDoubleList(reg); + TestGdalVectorFieldsReadWrite(); + } + + private static void TestAlgorithmArgsDoubleList(AlgorithmRegistry reg) + { + Console.WriteLine("Testing algorithm arguments with double list type..."); + var band = reg.Algorithms().OfName("raster").SubAlgorithms().OfName("footprint").Args().OfName("input-nodata"); + var doubles = Enumerable.Range(0, 50).Select(_ => Random.Shared.NextDouble()).ToArray(); + if (!band.SetAsDoubleList(doubles)) + throw new Exception("Failed to set double list."); + band.GetAsDoubleList(out var outDoubles); + if (!doubles.SequenceEqual(outDoubles)) + throw new Exception("Mismatch between set and retrieved double list."); + Console.WriteLine($"Successfully tested getting and setting algorithm arguments of type {Gdal.AlgorithmArgTypeName(band.GetType_())}."); + } + private static void TestAlgorithmArgsIntegerList(AlgorithmRegistry reg) + { + Console.WriteLine("Testing algorithm arguments with integer list type..."); + var band = reg.Algorithms().OfName("raster").SubAlgorithms().OfName("as-features").Args().OfName("band"); + var ints = Enumerable.Range(0, 50).Select(_ => Random.Shared.Next()).ToArray(); + if (!band.SetAsIntegerList(ints)) + throw new Exception("Failed to set integer list."); + band.GetAsIntegerList(out var outInts); + if (!ints.SequenceEqual(outInts)) + throw new Exception("Mismatch between set and retrieved integer list."); + Console.WriteLine($"Successfully tested getting and setting algorithm arguments of type {Gdal.AlgorithmArgTypeName(band.GetType_())}."); + } + private static void TestGdalVectorFieldsReadWrite() + { + Console.WriteLine("Testing feature fields with various types..."); + using var driver = Gdal.GetDriverByName("GeoJSON"); + if (File.Exists("test.geojson")) + File.Delete("test.geojson"); + using var ds = driver.CreateVector("test.geojson"); + + using var dLayer = ds.CreateLayer("double_layer"); + CreateFieldDefn(dLayer, "int32_field", FieldType.OFTInteger); + CreateFieldDefn(dLayer, "int64_field", FieldType.OFTInteger64); + CreateFieldDefn(dLayer, "double_field", FieldType.OFTReal); + CreateFieldDefn(dLayer, "string_field", FieldType.OFTString); + CreateFieldDefn(dLayer, "date_time_field", FieldType.OFTDateTime); + CreateFieldDefn(dLayer, "int32_list_field", FieldType.OFTIntegerList); + CreateFieldDefn(dLayer, "int64_list_field", FieldType.OFTInteger64List); + CreateFieldDefn(dLayer, "double_list_field", FieldType.OFTRealList); + CreateFieldDefn(dLayer, "string_list_field", FieldType.OFTStringList); + CreateFieldDefn(dLayer, "binary_field", FieldType.OFTBinary); + + using var dFeatureDef = dLayer.GetLayerDefn(); + using var feature = new Feature(dFeatureDef); + TestField( + "int32_field", + Random.Shared.Next(), + feature.SetField, + feature.GetFieldAsInteger); + + TestField( + "int64_field", + Random.Shared.NextInt64(), + feature.SetFieldInteger64, + feature.GetFieldAsInteger64); + + TestField( + "double_field", + Random.Shared.NextDouble(), + feature.SetField, + feature.GetFieldAsDouble); + + TestField( + "string_field", + UnicodeString, + feature.SetField, + feature.GetFieldAsString); + + TestField( + "date_time_field", + DateTime.Now, + feature.SetField, + feature.GetFieldAsDateTime, + TimesEqualAtMilliseconds); + + TestField( + "date_time_field", + DateTime.UtcNow, + feature.SetField, + feature.GetFieldAsDateTime, + TimesEqualAtMilliseconds); + + TestField( + "int32_list_field", + Enumerable.Range(0, 50).Select(_ => Random.Shared.Next()).ToArray(), + feature.SetFieldIntegerList, + n => feature.GetFieldAsIntegerList(n, out var _), + (a, b) => a.SequenceEqual(b)); + + TestField( + "int64_list_field", + Enumerable.Range(0, 50).Select(_ => Random.Shared.NextInt64()).ToArray(), + feature.SetFieldInteger64List, + n => feature.GetFieldAsInteger64List(n, out var _), + (a, b) => a.SequenceEqual(b)); + + TestField( + "double_list_field", + Enumerable.Range(0, 50).Select(_ => Random.Shared.NextDouble()).ToArray(), + feature.SetFieldDoubleList, + n => feature.GetFieldAsDoubleList(n, out var _), + (a, b) => a.SequenceEqual(b)); + + TestField( + "string_list_field", + Enumerable.Range(0, 50).Select(_ => Random.Shared.Next().ToString(CultureInfo.InvariantCulture)).ToArray(), + feature.SetFieldStringList, + feature.GetFieldAsStringList, + (a, b) => a.SequenceEqual(b)); + + TestField( + "binary_field", + Enumerable.Range(0, 50).Select(_ => (byte)Random.Shared.Next(0, 256)).ToArray(), + feature.SetFieldBinary, + n => feature.GetFieldAsBinary(n, out var _), + (a, b) => a.SequenceEqual(b)); + } + private static void CreateFieldDefn(Layer dLayer, string fieldName, FieldType type) + { + using var fieldDef = new FieldDefn(fieldName, type); + if (dLayer.CreateField(fieldDef, 1) != 0) + throw new Exception("Failed to create a field definition on layer."); + } + private static void TestField(string fieldName, T value, Action setField, Func getField, Func equals = null) + { + Console.WriteLine($" Testing field '{fieldName}' with type {typeof(T).Name}..."); + Console.WriteLine($" Setting '{fieldName}'"); + setField(fieldName, value); + Console.WriteLine($" Getting '{fieldName}'"); + var valuesGet = getField(fieldName); + Console.WriteLine($" Comparing '{fieldName}' set values with retrieved values"); + if (!equals?.Invoke(value, valuesGet) ?? !value.Equals(valuesGet)) + throw new Exception($"Mismatch between '{fieldName}' set and retrieved values."); + + Console.WriteLine($" Successfully set and got value from '{fieldName}'"); + } + private static bool TimesEqualAtMilliseconds(DateTime a, DateTime b) + => a.Ticks / 10_000 == b.Ticks / 10_000 && a.Kind == b.Kind; + + public static AlgorithmArg OfName(this IEnumerable algorithms, string name) + => algorithms.Single(arg => arg.GetName() == name); + public static IEnumerable OfTypeName(this IEnumerable algorithms, string typeName) + => algorithms.Where(arg => Gdal.AlgorithmArgTypeName(arg.GetType_()) == typeName); + public static IEnumerable OfListType(this IEnumerable algorithms, bool isList) + => algorithms.Where(arg => Gdal.AlgorithmArgTypeIsList(arg.GetType_()) == isList); + public static IEnumerable Args(this Algorithm algorithm) + => algorithm.GetArgNames().Select(argName => algorithm.GetArg(argName)); + public static Algorithm OfName(this IEnumerable algorithms, string name) + => algorithms.Single(alg => alg.GetName() == name); + public static IEnumerable SubAlgorithms(this Algorithm algorithm) + => algorithm.HasSubAlgorithms() ? algorithm.GetSubAlgorithmNames().Select(name => algorithm.InstantiateSubAlgorithm(name)) : Enumerable.Empty(); + public static IEnumerable Algorithms(this AlgorithmRegistry reg) + => reg.GetAlgNames().Select(algName => reg.InstantiateAlg(algName)); +} diff --git a/swig/csharp/apps/GDALGetHistogram.cs b/swig/csharp/apps/GDALGetHistogram.cs index d40d2514ba23..0cfa7f02fe82 100644 --- a/swig/csharp/apps/GDALGetHistogram.cs +++ b/swig/csharp/apps/GDALGetHistogram.cs @@ -88,9 +88,8 @@ public static void Main(string[] args) Console.WriteLine("Max=" + pdfMax); Console.WriteLine("Mean=" + pdfMean); Console.WriteLine("StdDev=" + pdfStdDev); - band.GetHistogram(-0.5, 255.5, 255, histData, 0, 1, - new Gdal.GDALProgressFuncDelegate(ProgressFunc), ""); - for (int i = 0; i < 255; i++) + band.GetHistogram(-0.5, 255.5, histData, false, true, new Gdal.GDALProgressFuncDelegate(ProgressFunc), " Band " + iBand); + for (int i = 0; i < histData.Length; i++) Console.Write(String.Format(CultureInfo.InvariantCulture, " {0:x}", histData[i])); Console.WriteLine(""); } diff --git a/swig/csharp/apps/GDALTestUtf8.cs b/swig/csharp/apps/GDALTestUtf8.cs index b85ca36ede9b..265854b368b5 100644 --- a/swig/csharp/apps/GDALTestUtf8.cs +++ b/swig/csharp/apps/GDALTestUtf8.cs @@ -1,3 +1,15 @@ +/****************************************************************************** + * + * Name: GDALTestUtf8.cs + * Project: GDAL CSharp Interface + * Purpose: A sample app to demonstrate getting and setting Unicode strings. + * Author: Michael Bucari-Tovo, mbucari1@gmail.com + * + ****************************************************************************** + * Copyright (c) 2026, Michael Bucari-Tovo + * + * SPDX-License-Identifier: MIT + *****************************************************************************/ using System; using System.Collections.Generic; using System.IO; @@ -113,19 +125,28 @@ private static void TestUnicodeDatasetLayerName() string fileName = UnicodeString + ".gdb"; if (File.Exists(fileName)) File.Delete(fileName); - using (OSGeo.OGR.Driver shpDriver = Ogr.GetDriverByName("OpenFileGDB")) + using (OSGeo.GDAL.Driver shpDriver = Gdal.GetDriverByName("OpenFileGDB")) { if (shpDriver != null) - using (DataSource shpSrc = shpDriver.CreateDataSource(fileName, null)) - shpSrc.CreateLayer("图层", null, wkbGeometryType.wkbPoint, null).Dispose(); + { + using Dataset shpSrc = shpDriver.CreateVector(fileName, null); + shpSrc.CreateLayer("图层", null, wkbGeometryType.wkbPoint, null).Dispose(); + using GeomFieldDefn geomFieldDefn = new GeomFieldDefn(UnicodeString, wkbGeometryType.wkbMultiPolygon); + shpSrc.CreateLayerFromGeomFieldDefn("层图2", geomFieldDefn).Dispose(); + } } - using (DataSource shpSrc = Ogr.Open(fileName, 0)) + using (Dataset shpSrc = Gdal.OpenEx(fileName)) { if (shpSrc != null) { - AssertEqual(fileName, shpSrc.GetName(), $"{nameof(DataSource)}.{nameof(shpSrc.GetName)}"); + AssertEqual(fileName, shpSrc.GetDescription(), $"{nameof(Dataset)}.{nameof(shpSrc.GetDescription)}"); using (Layer shpLyr = shpSrc.GetLayerByName("图层")) - AssertEqual("图层", shpLyr.GetName(), $"{nameof(Layer)}.{nameof(shpSrc.GetName)}"); + AssertEqual("图层", shpLyr.GetName(), $"{nameof(Layer)}.{nameof(shpLyr.GetName)}"); + using (Layer shpLyr = shpSrc.GetLayerByName("层图2")) + { + AssertEqual("层图2", shpLyr.GetName(), $"{nameof(Layer)}.{nameof(shpLyr.GetName)}"); + AssertEqual("wkbMultiPolygon", shpLyr.GetGeomType().ToString(), $"{nameof(Layer)}.{nameof(shpLyr.GetGeomType)}"); + } } } } @@ -144,8 +165,8 @@ private static void TestUnicodeFieldDefs() if (File.Exists(fileName)) File.Delete(fileName); - using (OSGeo.OGR.Driver shpDriver = Ogr.GetDriverByName("ESRI Shapefile")) - using (DataSource shpSrc = shpDriver.CreateDataSource(fileName, null)) + using (OSGeo.GDAL.Driver shpDriver = Gdal.GetDriverByName("ESRI Shapefile")) + using (Dataset shpSrc = shpDriver.CreateVector(fileName, null)) using (Layer shpLyr = shpSrc.CreateLayer(UnicodeString, null, wkbGeometryType.wkbPoint, new string[] { "ENCODING=UTF-8" })) using (FeatureDefn layerDef = shpLyr.GetLayerDefn()) { @@ -163,22 +184,20 @@ private static void TestUnicodeFieldDefs() } } } - using (DataSource shpSrc = Ogr.Open(fileName, 0)) + using (Dataset shpSrc = Gdal.OpenEx(fileName)) { if (shpSrc == null) throw new Exception($"Failed to open dataset: {shpSrc}"); - Layer shpLyr = shpSrc.GetLayerByName(UnicodeString) - ?? throw new Exception("Failed to get layer from shape file by name."); - int featureIndex = 0; - while (true) using (Feature feat = shpLyr.GetNextFeature()) + while (true) using (Feature feat = shpSrc.GetNextFeature(out Layer shpLyr, out double progress)) { + shpLyr?.Dispose(); if (feat == null) break; string fieldValue = feat.GetFieldAsString("图层"); - AssertEqual(nameFieldValues[featureIndex++], fieldValue, $"{nameof(Layer)}.{nameof(shpSrc.GetName)}"); + AssertEqual(nameFieldValues[featureIndex++], fieldValue, $"{nameof(Layer)}.{nameof(shpSrc.GetDescription)}"); } } } @@ -197,42 +216,32 @@ private static void TestUnicodeVrtFiles() if (File.Exists(vrtFile)) File.Delete(vrtFile); - using (SpatialReference webMerc = new SpatialReference("")) - { - webMerc.ImportFromEPSG(3857); - using (OSGeo.GDAL.Driver tifDriver = Gdal.GetDriverByName("GTiff")) - { - using (Dataset ds1 = tifDriver.Create(fileName1, 100, 100, 3, DataType.GDT_Byte, null)) - { - ds1.SetSpatialRef(webMerc); - ds1.SetGeoTransform(new double[] { 0, 1, 0, 0, 0, -1 }); - } + using SpatialReference webMerc = new SpatialReference(); + webMerc.ImportFromEPSG(3857); + using OSGeo.GDAL.Driver tifDriver = Gdal.GetDriverByName("GTiff"); + Dataset ds1 = tifDriver.Create(fileName1, 100, 100, 3, DataType.GDT_Byte); + ds1.SetSpatialRef(webMerc); + ds1.SetGeoTransform(new double[] { 0, 1, 0, 0, 0, -1 }); - using (Dataset ds2 = tifDriver.Create(fileName2, 100, 100, 3, DataType.GDT_Byte, null)) - { - ds2.SetSpatialRef(webMerc); - ds2.SetGeoTransform(new double[] { 100, 1, 0, 0, 0, -1 }); - } - } - } + Dataset ds2 = tifDriver.Create(fileName2, 100, 100, 3, DataType.GDT_Byte); + ds2.SetSpatialRef(webMerc); + ds2.SetGeoTransform(new double[] { 100, 1, 0, 0, 0, -1 }); - Gdal.BuildVRT(vrtFile, new string[] { fileName1, fileName2 }, null, null, null).Dispose(); - using (Dataset vrt = Gdal.Open(vrtFile, Access.GA_ReadOnly)) - { - if (vrt.RasterXSize != 200) - throw new Exception($"Expected VRT width of 200, got {vrt.RasterXSize}"); + Gdal.BuildVRT(vrtFile, new Dataset[] { ds1, ds2 }, null).Dispose(); + using Dataset vrt = Gdal.Open(vrtFile, Access.GA_ReadOnly); + if (vrt.RasterXSize != 200) + throw new Exception($"Expected VRT width of 200, got {vrt.RasterXSize}"); - if (vrt.RasterYSize != 100) - throw new Exception($"Expected VRT height of 100, got {vrt.RasterYSize}"); + if (vrt.RasterYSize != 100) + throw new Exception($"Expected VRT height of 100, got {vrt.RasterYSize}"); - string[] list = vrt.GetFileList(); - if (list.Length != 3) - throw new Exception($"Expected 3 files in VRT file list, got {list.Length}"); + string[] list = vrt.GetFileList(); + if (list.Length != 3) + throw new Exception($"Expected 3 files in VRT file list, got {list.Length}"); - AssertEqual(vrtFile, list[0], $"{nameof(Dataset)}.{nameof(vrt.GetFileList)}()[0]"); - AssertEqual(fileName1, list[1], $"{nameof(Dataset)}.{nameof(vrt.GetFileList)}()[1]"); - AssertEqual(fileName2, list[2], $"{nameof(Dataset)}.{nameof(vrt.GetFileList)}()[2]"); - } + AssertEqual(vrtFile, list[0], $"{nameof(Dataset)}.{nameof(vrt.GetFileList)}()[0]"); + AssertEqual(fileName1, list[1], $"{nameof(Dataset)}.{nameof(vrt.GetFileList)}()[1]"); + AssertEqual(fileName2, list[2], $"{nameof(Dataset)}.{nameof(vrt.GetFileList)}()[2]"); } private static void TestCSharpExceptions() { @@ -326,4 +335,3 @@ private static TDelegate GetPrivateGdalMethod(string methodName) wher ?? throw new MissingMethodException($"Could not get non-public, static method {methodName} from {nameof(Gdal)}"); } } - diff --git a/swig/csharp/apps/GDALWrite.cs b/swig/csharp/apps/GDALWrite.cs index 0dbfc3e25eb8..ad8931d32b0f 100644 --- a/swig/csharp/apps/GDALWrite.cs +++ b/swig/csharp/apps/GDALWrite.cs @@ -107,7 +107,10 @@ public static void Main(string[] args) new GCP(44.5, 26.5, 0, 0, 100, "info2", "id2"), new GCP(45.5, 26.5, 0, 100, 100, "info3", "id3") }; - ds.SetGCPs(GCPs, ""); + ds.SetGCPs(GCPs); + CompareGCPs(GCPs, ds.GetGCPs()); + ds.SetGCPs2(GCPs); + CompareGCPs(GCPs, ds.GetGCPs()); using (Band band = ds.GetRasterBand(1)) { @@ -128,4 +131,25 @@ public static void Main(string[] args) ds.FlushCache(); } } + + private static void CompareGCPs(GCP[] set1, GCP[] set2) + { + if (set1.Length != set2.Length) ErrorAndClose("GCP count mismatch"); + for (int i = 0; i < set1.Length; i++) + { + if (set1[i].Id != set2[i].Id) ErrorAndClose("GCP id mismatch"); + if (set1[i].Info != set2[i].Info) ErrorAndClose("GCP info mismatch"); + if (set1[i].GCPPixel != set2[i].GCPPixel) ErrorAndClose("GCP pixel mismatch"); + if (set1[i].GCPLine != set2[i].GCPLine) ErrorAndClose("GCP line mismatch"); + if (set1[i].GCPX != set2[i].GCPX) ErrorAndClose("GCP X mismatch"); + if (set1[i].GCPY != set2[i].GCPY) ErrorAndClose("GCP Y mismatch"); + if (set1[i].GCPZ != set2[i].GCPZ) ErrorAndClose("GCP Z mismatch"); + } + } + + private static void ErrorAndClose(string message) + { + Console.WriteLine("Error: " + message); + System.Environment.Exit(-1); + } } diff --git a/swig/csharp/apps/OSRTransform.cs b/swig/csharp/apps/OSRTransform.cs index 91cb00688e9b..20ffd61f3f1b 100644 --- a/swig/csharp/apps/OSRTransform.cs +++ b/swig/csharp/apps/OSRTransform.cs @@ -37,16 +37,15 @@ public static void Main(string[] args) /* -------------------------------------------------------------------- */ /* Initialize srs */ /* -------------------------------------------------------------------- */ - int nvalues; int[] confidence_values; using (SpatialReference src = new SpatialReference("")) using (SpatialReference dst = new SpatialReference("")) { src.ImportFromProj4("+proj=latlong +datum=WGS84 +no_defs"); - var srName = src.FindMatches(new string[] { "", null }, out nvalues, out confidence_values).FirstOrDefault()?.GetName() ?? "NotFound"; + var srName = src.FindMatches(new string[] { "", null }, out confidence_values).FirstOrDefault()?.GetName() ?? "NotFound"; Console.WriteLine($"SOURCE Name:'{srName}' IsGeographic:{src.IsGeographic()} IsProjected:{src.IsProjected()}"); dst.ImportFromProj4("+proj=somerc +lat_0=47.14439372222222 +lon_0=19.04857177777778 +x_0=650000 +y_0=200000 +ellps=GRS67 +units=m +no_defs"); - srName = dst.FindMatches(new string[] { "", null }, out nvalues, out confidence_values).FirstOrDefault()?.GetName() ?? "NotFound"; + srName = dst.FindMatches(new string[] { "", null }, out confidence_values).FirstOrDefault()?.GetName() ?? "NotFound"; Console.WriteLine($"DEST Name:'{srName}' IsGeographic:{dst.IsGeographic()} IsProjected:{dst.IsProjected()}"); /* -------------------------------------------------------------------- */ /* making the transform */ diff --git a/swig/csharp/apps/createdata.cs b/swig/csharp/apps/createdata.cs index d8cacc9f7659..b64d8681c2a5 100644 --- a/swig/csharp/apps/createdata.cs +++ b/swig/csharp/apps/createdata.cs @@ -256,22 +256,34 @@ public static void ReportFeature(Feature feat, FeatureDefn def) if (feat.GetStyleString() != null) Console.WriteLine(" Style = " + feat.GetStyleString()); - using (Geometry geom = feat.GetGeometryRef()) - using (Envelope env = new Envelope()) - if (geom != null) + using Geometry geom = feat.GetGeometryRef(); + using Envelope env = new Envelope(); + if (geom != null) + { + Console.WriteLine(" " + geom.GetGeometryName() + + "(" + geom.GetGeometryType() + ")"); + + geom.GetEnvelope(env); + Console.WriteLine(" ENVELOPE: " + env.MinX + "," + env.MaxX + "," + + env.MinY + "," + env.MaxY); + + string geom_wkt; + geom.ExportToWkt(out geom_wkt); + + Console.WriteLine(" " + geom_wkt); + Console.WriteLine(); + + using Geometry envelopePoly = Ogr.CreateGeometryFromEnvelope(env); + byte[] wkbBts = new byte[envelopePoly.WkbLongSize]; + envelopePoly.ExportToIsoWkb(wkbBts); + using Geometry envelopePoly2 = Geometry.CreateFromWkb(wkbBts); + envelopePoly.ExportToWkt(out string env_wkt); + envelopePoly2.ExportToWkt(out string env_wkt2); + if (env_wkt != env_wkt2) { - Console.WriteLine(" " + geom.GetGeometryName() + - "(" + geom.GetGeometryType() + ")"); - - geom.GetEnvelope(env); - Console.WriteLine(" ENVELOPE: " + env.MinX + "," + env.MaxX + "," + - env.MinY + "," + env.MaxY); - - string geom_wkt; - geom.ExportToWkt(out geom_wkt); - Console.WriteLine(" " + geom_wkt); - - Console.WriteLine(""); + Console.WriteLine("Envelope WKT mismatch: " + env_wkt + " vs " + env_wkt2); + Environment.Exit(-1); } + } } } diff --git a/swig/include/Algorithm.i b/swig/include/Algorithm.i index 49f8f38bc37b..54768fb76c4f 100644 --- a/swig/include/Algorithm.i +++ b/swig/include/Algorithm.i @@ -154,7 +154,7 @@ public: } %clear char **; -#if defined(SWIGPYTHON) +#if defined(SWIGPYTHON) || defined(SWIGCSHARP) void GetDefaultAsIntegerList(int *nLen, const int **pList) { size_t nLenSizet = 0; *pList = GDALAlgorithmArgGetDefaultAsIntegerList(self, &nLenSizet); @@ -162,7 +162,7 @@ public: } #endif -#if defined(SWIGPYTHON) +#if defined(SWIGPYTHON) || defined(SWIGCSHARP) void GetDefaultAsDoubleList(int *nLen, const double **pList) { size_t nLenSizet = 0; *pList = GDALAlgorithmArgGetDefaultAsDoubleList(self, &nLenSizet); @@ -248,7 +248,7 @@ public: } %clear char **; -#if defined(SWIGPYTHON) +#if defined(SWIGPYTHON) || defined(SWIGCSHARP) void GetAsIntegerList(int *nLen, const int **pList) { size_t nLenSizet = 0; *pList = GDALAlgorithmArgGetAsIntegerList(self, &nLenSizet); @@ -256,7 +256,7 @@ public: } #endif -#if defined(SWIGPYTHON) +#if defined(SWIGPYTHON) || defined(SWIGCSHARP) void GetAsDoubleList(int *nLen, const double **pList) { size_t nLenSizet = 0; *pList = GDALAlgorithmArgGetAsDoubleList(self, &nLenSizet); @@ -302,7 +302,7 @@ public: return GDALAlgorithmArgSetDataset(self, ds); } -#if defined(SWIGPYTHON) +#if defined(SWIGPYTHON) || defined(SWIGCSHARP) bool SetDatasets(int object_list_count, GDALDatasetShadow** poObjects) { return GDALAlgorithmArgSetDatasets(self, object_list_count, poObjects); } diff --git a/swig/include/Band.i b/swig/include/Band.i index 07892c7d3c0e..eb38b8f6cd86 100644 --- a/swig/include/Band.i +++ b/swig/include/Band.i @@ -281,6 +281,12 @@ public: int Checksum( int xoff, int yoff, int xsize, int ysize) { return GDALChecksumImage( self, xoff, yoff, xsize, ysize ); } +#elif defined(SWIGCSHARP) + int Checksum( int xoff = 0, int yoff = 0, int xsize = 0, int ysize = 0) { + if (xsize == 0) xsize = GDALGetRasterBandXSize( self ); + if (ysize == 0) ysize = GDALGetRasterBandYSize( self ); + return GDALChecksumImage( self, xoff, yoff, xsize, ysize ); + } #else %apply (int *optional_int) {(int*)}; %feature ("kwargs") Checksum; @@ -418,11 +424,41 @@ public: callback, callback_data ); return err; } +#elif defined(SWIGCSHARP) +/* ignore overload which splits multi-argument typemap*/ +%ignore GetHistogram(double,double,int); +%apply (int nList, int *pList) {(int histogram, int *panHistogram)}; + CPLErr GetHistogram( double min = -0.5, double max = 255.5, + int histogram=0, int *panHistogram = NULL, + bool include_out_of_range = FALSE, + bool approx_ok = TRUE, + GDALProgressFunc callback = NULL, + void* callback_data=NULL ) { + CPLErrorReset(); + CPLErr err = GDALGetRasterHistogram( self, min, max, histogram, panHistogram, + static_cast(include_out_of_range), static_cast(approx_ok), + callback, callback_data ); + return err; + } +%clear (int histogram, int *panHistogram); +/* ignore overload which splits multi-argument typemap*/ +%ignore GetHistogramEx(double,double,int); +%apply (int nList, GUIntBig *pList) {(int histogram, GUIntBig *panHistogram)}; + CPLErr GetHistogramEx( double min = -0.5, double max = 255.5, + int histogram=0, GUIntBig *panHistogram = NULL, + bool include_out_of_range = FALSE, + bool approx_ok = TRUE, + GDALProgressFunc callback = NULL, + void* callback_data=NULL ) { + CPLErrorReset(); + CPLErr err = GDALGetRasterHistogramEx( self, min, max, histogram, panHistogram, + static_cast(include_out_of_range), static_cast(approx_ok), + callback, callback_data ); + return err; + } +%clear (int histogram, GUIntBig *panHistogram); #else #ifndef SWIGJAVA -#if defined(SWIGCSHARP) -%apply (int inout[ANY]) {int *panHistogram}; -#endif %feature( "kwargs" ) GetHistogram; CPLErr GetHistogram( double min=-0.5, double max=255.5, @@ -438,9 +474,6 @@ public: callback, callback_data ); return err; } -#if defined(SWIGCSHARP) -%clear int *panHistogram; -#endif #endif #endif @@ -454,18 +487,33 @@ CPLErr GetDefaultHistogram( double *min_ret=NULL, double *max_ret=NULL, int *buc ppanHistogram, force, callback, callback_data ); } -#else -#ifndef SWIGJAVA -%feature ("kwargs") GetDefaultHistogram; -CPLErr GetDefaultHistogram( double *min_ret=NULL, double *max_ret=NULL, int *buckets_ret = NULL, - int **ppanHistogram = NULL, int force = 1, +#elif defined(SWIGCSHARP) +/* ignore overload which splits multi-argument typemap*/ +%ignore GetDefaultHistogramEx(double*,double*,int*); +%apply (int *hasval) {int *count}; +%apply (int *nLen, GUIntBig **pList_free) {(int *histogram, GUIntBig **ppanHistogram)}; +CPLErr GetDefaultHistogramEx( double *min_ret, double *max_ret, int *histogram, + GUIntBig **ppanHistogram, bool force = TRUE, GDALProgressFunc callback = NULL, void* callback_data=NULL ) { - return GDALGetDefaultHistogram( self, min_ret, max_ret, buckets_ret, + return GDALGetDefaultHistogramEx( self, min_ret, max_ret, histogram, ppanHistogram, force, callback, callback_data ); } -#endif +%clear (int *count, GUIntBig **ppanHistogram); +/* ignore overload which splits multi-argument typemap*/ +%ignore GetDefaultHistogram(double*,double*,int*); +%apply (int *nLen, int **pList_free) {(int *histogram, int **ppanHistogram)}; +CPLErr GetDefaultHistogram( double *min_ret, double *max_ret, int *histogram, + int **ppanHistogram, bool force = TRUE, + GDALProgressFunc callback = NULL, + void* callback_data=NULL ) { + return GDALGetDefaultHistogram( self, min_ret, max_ret, histogram, + ppanHistogram, force, + callback, callback_data ); +} +%clear (int *histogram, int **ppanHistogram); +%clear int *count; #endif #if defined(SWIGPYTHON) @@ -477,17 +525,23 @@ CPLErr SetDefaultHistogram( double min, double max, } %clear (int buckets_in, GUIntBig *panHistogram_in); #else -#if defined(SWIGJAVA) %apply (int nList, int* pList) {(int buckets_in, int *panHistogram_in)} -#endif CPLErr SetDefaultHistogram( double min, double max, int buckets_in, int *panHistogram_in ) { return GDALSetDefaultHistogram( self, min, max, buckets_in, panHistogram_in ); } -#if defined(SWIGJAVA) %clear (int buckets_in, int *panHistogram_in); #endif + +#if defined(SWIGCSHARP) +%apply (int nList, GUIntBig* pList) {(int buckets_in, GUIntBig *panHistogram_in)} +CPLErr SetDefaultHistogramEx( double min, double max, + int buckets_in, GUIntBig *panHistogram_in ) { + return GDALSetDefaultHistogramEx( self, min, max, + buckets_in, panHistogram_in ); +} +%clear (int buckets_in, GUIntBig *panHistogram_in); #endif bool HasArbitraryOverviews() { @@ -628,6 +682,18 @@ CPLErr SetDefaultHistogram( double min, double max, #ifdef SWIGPYTHON %feature("kwargs") AdviseRead; #endif +#ifdef SWIGCSHARP +CPLErr AdviseRead( int xoff, int yoff, int xsize, int ysize, + int buf_xsize = 0, int buf_ysize = 0, + GDALDataType buf_type = GDT_Byte, + char** options = NULL ){ + + if (buf_xsize == 0) buf_xsize = xsize; + if (buf_ysize == 0) buf_ysize = ysize; + return GDALRasterAdviseRead(self, xoff, yoff, xsize, ysize, + buf_xsize, buf_ysize, buf_type, options); +} +#else %apply (int *optional_int) { (GDALDataType *buf_type) }; CPLErr AdviseRead( int xoff, int yoff, int xsize, int ysize, int *buf_xsize = 0, int *buf_ysize = 0, @@ -645,6 +711,7 @@ CPLErr AdviseRead( int xoff, int yoff, int xsize, int ysize, return GDALRasterAdviseRead(self, xoff, yoff, xsize, ysize, nxsize, nysize, ntype, options); } +#endif %clear (GDALDataType *buf_type); %clear (int band_list, int *pband_list ); @@ -766,20 +833,12 @@ CPLErr AdviseRead( int xoff, int yoff, int xsize, int ysize, } %newobject MaximumOfNBands; -#ifdef SWIGCSHARP - %apply GDALRasterBandShadow OBJPTRS_STATIC[] {GDALRasterBandShadow **bands}; -#else %apply (int object_list_count, GDALRasterBandShadow **poObjects) {(int band_count, GDALRasterBandShadow **bands)}; -#endif static GDALComputedRasterBandShadow* MaximumOfNBands(int band_count, GDALRasterBandShadow** bands) { return GDALMaximumOfNBands(band_count, bands); } -#ifdef SWIGCSHARP - %clear GDALRasterBandShadow **bands; -#else %clear (int band_count, GDALRasterBandShadow **bands); -#endif %newobject MaxConstant; GDALComputedRasterBandShadow* MaxConstant(double constant) @@ -788,20 +847,12 @@ CPLErr AdviseRead( int xoff, int yoff, int xsize, int ysize, } %newobject MinimumOfNBands; -#ifdef SWIGCSHARP - %apply GDALRasterBandShadow OBJPTRS_STATIC[] {GDALRasterBandShadow **bands}; -#else %apply (int object_list_count, GDALRasterBandShadow **poObjects) {(int band_count, GDALRasterBandShadow **bands)}; -#endif static GDALComputedRasterBandShadow* MinimumOfNBands(int band_count, GDALRasterBandShadow** bands) { return GDALMinimumOfNBands(band_count, bands); } -#ifdef SWIGCSHARP - %clear GDALRasterBandShadow **bands; -#else %clear (int band_count, GDALRasterBandShadow **bands); -#endif %newobject MinConstant; GDALComputedRasterBandShadow* MinConstant(double constant) @@ -810,20 +861,12 @@ CPLErr AdviseRead( int xoff, int yoff, int xsize, int ysize, } %newobject MeanOfNBands; -#ifdef SWIGCSHARP - %apply GDALRasterBandShadow OBJPTRS_STATIC[] {GDALRasterBandShadow **bands}; -#else %apply (int object_list_count, GDALRasterBandShadow **poObjects) {(int band_count, GDALRasterBandShadow **bands)}; -#endif static GDALComputedRasterBandShadow* MeanOfNBands(int band_count, GDALRasterBandShadow** bands) { return GDALMeanOfNBands(band_count, bands); } -#ifdef SWIGCSHARP - %clear GDALRasterBandShadow **bands; -#else %clear (int band_count, GDALRasterBandShadow **bands); -#endif } /* %extend */ diff --git a/swig/include/Dataset.i b/swig/include/Dataset.i index 0c9dd5a2cc38..6b4b1edd5f60 100644 --- a/swig/include/Dataset.i +++ b/swig/include/Dataset.i @@ -404,7 +404,6 @@ public: #if defined(SWIGCSHARP) - %feature( "kwargs" ) GetExtent; CPLErr GetExtent(OGREnvelope* extent, OSRSpatialReferenceShadow* srs = NULL) { return GDALGetExtent(self, extent, srs); } @@ -423,7 +422,6 @@ public: #if defined(SWIGCSHARP) - %feature( "kwargs" ) GetExtentWGS84LongLat; CPLErr GetExtentWGS84LongLat(OGREnvelope* extent) { return GDALGetExtentWGS84LongLat(self, extent); } @@ -443,14 +441,13 @@ public: // The (int,int*) arguments are typemapped. The name of the first argument // becomes the kwarg name for it. -#ifndef SWIGCSHARP -#ifndef SWIGJAVA + +/* ignore overload which splits multi-argument typemap*/ +%ignore BuildOverviews(const char *,int); +#ifdef SWIGPYTHON %feature("kwargs") BuildOverviews; #endif %apply (int nList, int* pList) { (int overviewlist, int *pOverviews) }; -#else -%apply (void *buffer_ptr) {int *pOverviews}; -#endif #ifdef SWIGJAVA %apply (const char* stringWithDefaultValue) {const char* resampling}; int BuildOverviews( const char *resampling, @@ -475,11 +472,7 @@ public: callback_data, options); } -#ifndef SWIGCSHARP %clear (int overviewlist, int *pOverviews); -#else -%clear (int *pOverviews); -#endif #ifdef SWIGJAVA %clear (const char *resampling); #endif @@ -492,7 +485,6 @@ public: return GDALGetGCPProjection( self ); } -#ifndef SWIGCSHARP %newobject GetGCPSpatialRef; OSRSpatialReferenceShadow *GetGCPSpatialRef() { OGRSpatialReferenceH ref = GDALGetGCPSpatialRef(self); @@ -500,24 +492,20 @@ public: ref = OSRClone( ref ); return (OSRSpatialReferenceShadow*) ref; } -#endif -#ifndef SWIGCSHARP void GetGCPs( int *nGCPs, GDAL_GCP const **pGCPs ) { *nGCPs = GDALGetGCPCount( self ); *pGCPs = GDALGetGCPs( self ); } - CPLErr SetGCPs( int nGCPs, GDAL_GCP const *pGCPs, const char *pszGCPProjection ) { + CPLErr SetGCPs( int nGCPs, GDAL_GCP const *pGCPs, const char *pszGCPProjection = "") { return GDALSetGCPs( self, nGCPs, pGCPs, pszGCPProjection ); } - CPLErr SetGCPs2( int nGCPs, GDAL_GCP const *pGCPs, OSRSpatialReferenceShadow* hSRS ) { + CPLErr SetGCPs2( int nGCPs, GDAL_GCP const *pGCPs, OSRSpatialReferenceShadow* hSRS = NULL) { return GDALSetGCPs2( self, nGCPs, pGCPs, (OGRSpatialReferenceH)hSRS ); } -#endif - CPLErr FlushCache() { return GDALFlushCache( self ); } @@ -602,14 +590,26 @@ public: %clear (GIntBig buf_len, char *buf_string); #endif -#ifdef SWIGPYTHON -%feature("kwargs") AdviseRead; -#endif %apply (int *optional_int) { (GDALDataType *buf_type) }; -#if defined(SWIGCSHARP) -%apply int PINNED[] {int *pband_list}; -#else %apply (int nList, int *pList ) { (int band_list, int *pband_list ) }; +#ifdef SWIGCSHARP +/* ignore overload which splits multi-argument typemap*/ +%ignore AdviseRead(int,int,int,int,int,int,GDALDataType,int); +CPLErr AdviseRead( int xoff, int yoff, int xsize, int ysize, + int buf_xsize = 0, int buf_ysize = 0, + GDALDataType buf_type = GDT_Byte, + int band_list = 0, int *pband_list = 0, + char** options = NULL ){ + + if (buf_xsize == 0) buf_xsize = xsize; + if (buf_ysize == 0) buf_ysize = ysize; + return GDALDatasetAdviseRead(self, xoff, yoff, xsize, ysize, + buf_xsize, buf_ysize, buf_type, + band_list, pband_list, options); +} +#else +#ifdef SWIGPYTHON +%feature("kwargs") AdviseRead; #endif CPLErr AdviseRead( int xoff, int yoff, int xsize, int ysize, int *buf_xsize = 0, int *buf_ysize = 0, @@ -634,12 +634,9 @@ CPLErr AdviseRead( int xoff, int yoff, int xsize, int ysize, nxsize, nysize, ntype, band_list, pband_list, options); } +#endif %clear (GDALDataType *buf_type); -#if defined(SWIGCSHARP) -%clear int *pband_list; -#else %clear (int band_list, int *pband_list ); -#endif /* NEEDED */ /* GetSubDatasets */ @@ -912,10 +909,8 @@ CPLErr AdviseRead( int xoff, int yoff, int xsize, int ysize, #endif /* PYTHON */ -#if defined(SWIGPYTHON) || defined(SWIGJAVA) - /* Note that datasources own their layers */ -#ifndef SWIGJAVA +#ifdef SWIGPYTHON %feature( "kwargs" ) CreateLayer; #endif OGRLayerShadow *CreateLayer(const char* name, @@ -931,7 +926,7 @@ CPLErr AdviseRead( int xoff, int yoff, int xsize, int ysize, } /* Note that datasources own their layers */ -#ifndef SWIGJAVA +#ifdef SWIGPYTHON %feature( "kwargs" ) CreateLayer; #endif OGRLayerShadow *CreateLayerFromGeomFieldDefn(const char* name, @@ -944,7 +939,7 @@ CPLErr AdviseRead( int xoff, int yoff, int xsize, int ysize, return layer; } -#ifndef SWIGJAVA +#ifdef SWIGPYTHON %feature( "kwargs" ) CopyLayer; #endif %apply Pointer NONNULL {OGRLayerShadow *src_layer}; @@ -966,11 +961,8 @@ CPLErr AdviseRead( int xoff, int yoff, int xsize, int ysize, return GDALDatasetIsLayerPrivate(self, index); } - - - -#ifdef SWIGPYTHON %newobject GetNextFeature; +#ifdef SWIGPYTHON %feature( "kwargs" ) GetNextFeature; OGRFeatureShadow* GetNextFeature( bool include_layer = true, bool include_pct = false, @@ -985,20 +977,33 @@ CPLErr AdviseRead( int xoff, int yoff, int xsize, int ysize, *ppoBelongingLayer = (OGRLayerShadow*)hLayer; return feat; } -#else +#elif defined(SWIGJAVA) // FIXME: return layer -%newobject GetNextFeature; OGRFeatureShadow* GetNextFeature() { return (OGRFeatureShadow*)GDALDatasetGetNextFeature( self, NULL, NULL, NULL, NULL ); } +#else + %apply double* OUTPUT {double* pdfProgressPct}; + OGRFeatureShadow *GetNextFeature( OGRLayerShadow** ppoBelongingLayer, + double* pdfProgressPct, + GDALProgressFunc callback = NULL, + void* callback_data=NULL ) + { + OGRLayerH hLayer = NULL; + OGRFeatureShadow* feat = (OGRFeatureShadow*)GDALDatasetGetNextFeature( self, &hLayer, pdfProgressPct, + callback, callback_data ); + *ppoBelongingLayer = (OGRLayerShadow*)hLayer; + return feat; + } + %clear double* pdfProgressPct; #endif bool TestCapability(const char * cap) { return (GDALDatasetTestCapability(self, cap) > 0); } -#ifndef SWIGJAVA +#ifdef SWIGPYTHON %feature( "kwargs" ) ExecuteSQL; #endif %apply Pointer NONNULL {const char * statement}; @@ -1027,10 +1032,7 @@ CPLErr AdviseRead( int xoff, int yoff, int xsize, int ysize, GDALDatasetSetStyleTable(self, (OGRStyleTableH) table); } -#endif /* defined(SWIGPYTHON) || defined(SWIGJAVA) */ - - -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) OGRLayerShadow *GetLayerByIndex( int index ) { #elif SWIGPYTHON OGRLayerShadow *GetLayerByIndex( int index=0) { @@ -1055,29 +1057,11 @@ CPLErr AdviseRead( int xoff, int yoff, int xsize, int ysize, return GDALDatasetGetLayerCount(self); } -#ifdef SWIGCSHARP - - %newobject GetNextFeature; - OGRFeatureShadow *GetNextFeature( OGRLayerShadow** ppoBelongingLayer = NULL, - double* pdfProgressPct = NULL, - GDALProgressFunc callback = NULL, - void* callback_data=NULL ) - { - OGRLayerH hLayer = NULL; - OGRFeatureShadow* feat = (OGRFeatureShadow*)GDALDatasetGetNextFeature( self, &hLayer, pdfProgressPct, - callback, callback_data ); - *ppoBelongingLayer = (OGRLayerShadow*)hLayer; - return feat; - } - - -#endif - OGRErr AbortSQL() { return GDALDatasetAbortSQL(self); } -#ifndef SWIGJAVA +#ifdef SWIGPYTHON %feature( "kwargs" ) StartTransaction; #endif OGRErr StartTransaction(int force = FALSE) diff --git a/swig/include/MultiDimensional.i b/swig/include/MultiDimensional.i index 81bb357f20ae..0673a136c08d 100644 --- a/swig/include/MultiDimensional.i +++ b/swig/include/MultiDimensional.i @@ -222,11 +222,7 @@ public: } %newobject CreateAttribute; -#if defined(SWIGCSHARP) -%apply GUIntBig PINNED[] {GUIntBig *sizes}; -#else %apply (int nList, GUIntBig *pList) {(int dimensions, GUIntBig *sizes)}; -#endif GDALAttributeHS *CreateAttribute( const char *name, int dimensions, GUIntBig *sizes, @@ -569,11 +565,7 @@ public: } %clear char **; -#if defined(SWIGCSHARP) -%apply GUIntBig PINNED[] {GUIntBig* newSizes}; -#else %apply (int nList, GUIntBig* pList) {(int newDimensions, GUIntBig* newSizes)}; -#endif CPLErr Resize( int newDimensions, GUIntBig* newSizes, char** options = NULL ) { if( static_cast(newDimensions) != GDALMDArrayGetDimensionCount(self) ) { @@ -583,11 +575,7 @@ public: } return GDALMDArrayResize( self, newSizes, options ) ? CE_None : CE_Failure; } -#if defined(SWIGCSHARP) -%clear GUIntBig* newSizes; -#else %clear (int newDimensions, GUIntBig* newSizes); -#endif #if defined(SWIGPYTHON) %apply Pointer NONNULL {GDALExtendedDataTypeHS* buffer_datatype}; @@ -932,11 +920,7 @@ public: #endif %newobject CreateAttribute; -#if defined(SWIGCSHARP) -%apply GUIntBig PINNED[] {GUIntBig *sizes}; -#else %apply (int nList, GUIntBig *pList) {(int dimensions, GUIntBig *sizes)}; -#endif GDALAttributeHS *CreateAttribute( const char *name, int dimensions, GUIntBig *sizes, @@ -1131,11 +1115,7 @@ public: } %newobject Transpose; -#if defined(SWIGCSHARP) -%apply int PINNED[] {int* mapInts}; -#else %apply (int nList, int* pList) { (int axisMap, int* mapInts) }; -#endif GDALMDArrayHS* Transpose(int axisMap, int* mapInts) { return GDALMDArrayTranspose(self, axisMap, mapInts); @@ -1290,6 +1270,8 @@ public: return GDALMDArrayGetOverview(self, idx); } +/* ignore overload which splits multi-argument typemap*/ +%ignore BuildOverviews(char const *,int); %apply (int nList, int* pList) { (int overviewlist, int *pOverviews) }; CPLErr BuildOverviews( const char *resampling = "NEAREST", int overviewlist = 0, int *pOverviews = 0, @@ -1647,7 +1629,7 @@ public: return GDALExtendedDataTypeCreateStringEx(nMaxStringLength, eSubType); } -#if defined(SWIGPYTHON) +#if defined(SWIGPYTHON) || defined(SWIGCSHARP) %newobject CreateCompound; %apply (int object_list_count, GDALEDTComponentHS **poObjects) {(int nComps, GDALEDTComponentHS **comps)}; static GDALExtendedDataTypeHS* CreateCompound(const char* name, diff --git a/swig/include/Operations.i b/swig/include/Operations.i index 799aec2c7cdc..d66578bcfd78 100644 --- a/swig/include/Operations.i +++ b/swig/include/Operations.i @@ -179,9 +179,9 @@ int ComputeProximity( GDALRasterBandShadow *srcBand, %apply Pointer NONNULL {GDALDatasetShadow *dataset, OGRLayerShadow *layer}; -#ifdef SWIGJAVA %apply (int nList, int *pList ) { (int bands, int *band_list ) }; %apply (int nList, double *pList ) { (int burn_values, double *burn_values_list ) }; +#ifdef SWIGJAVA %inline %{ int RasterizeLayer( GDALDatasetShadow *dataset, int bands, int *band_list, @@ -221,10 +221,51 @@ int RasterizeLayer( GDALDatasetShadow *dataset, return eErr; } %} +#elif defined(SWIGCSHARP) +/* ignore overload which splits multi-argument typemap*/ +%ignore RasterizeLayers(GDALDatasetShadow *,int,int *, int, OGRLayerShadow **,GDALTransformerFunc,void *,int); +%apply (int object_list_count, OGRLayerShadow **poObjects) { (int layers, OGRLayerShadow **pLayers) }; +%inline %{ +int RasterizeLayers( GDALDatasetShadow *dataset, + int bands, int *band_list, + int layers, OGRLayerShadow **pLayers, + GDALTransformerFunc pfnTransformer = NULL, + void *pTransformArg = NULL, + int burn_values = 0, double *burn_values_list = NULL, + char **options = NULL, + GDALProgressFunc callback=NULL, + void* callback_data=NULL) { + + CPLErr eErr; + + CPLErrorReset(); + + int req_butn_values = bands * layers; + if( burn_values == 0 ) + { + burn_values_list = (double *) CPLMalloc(sizeof(double)*req_butn_values); + for( int i = 0; i < req_butn_values; i++ ) + burn_values_list[i] = 255.0; + } + else if( burn_values < req_butn_values ) + { + CPLError( CE_Failure, CPLE_AppDefined, + "Did not get the expected number of burn values in RasterizeLayer()" ); + return CE_Failure; + } + + eErr = GDALRasterizeLayers( dataset, bands, band_list, + layers, (OGRLayerH*)pLayers, + pfnTransformer, pTransformArg, + burn_values_list, options, + callback, callback_data ); + if( burn_values == 0 ) + CPLFree( burn_values_list ); + + return eErr; +} %} #else %feature( "kwargs" ) RasterizeLayer; -%apply (int nList, int *pList ) { (int bands, int *band_list ) }; -%apply (int nList, double *pList ) { (int burn_values, double *burn_values_list ) }; %inline %{ int RasterizeLayer( GDALDatasetShadow *dataset, int bands, int *band_list, @@ -373,11 +414,7 @@ int SieveFilter( GDALRasterBandShadow *srcBand, #ifndef SWIGJAVA %feature( "kwargs" ) RegenerateOverviews; #endif /* SWIGJAVA */ -#ifndef SWIGCSHARP %apply (int object_list_count, GDALRasterBandShadow **poObjects) {(int overviewBandCount, GDALRasterBandShadow **overviewBands)}; -#else -%apply GDALRasterBandShadow OBJPTRS_STATIC[] {GDALRasterBandShadow** overviewBands} -#endif /* SWIGCSHARP */ #ifdef SWIGJAVA %apply (const char* stringWithDefaultValue) {const char *resampling}; #endif /* SWIGJAVA */ @@ -485,8 +522,10 @@ int wrapper_GridCreate( char* algorithmOptions, /* ContourGenerate() */ /************************************************************************/ -#ifndef SWIGJAVA +#ifdef SWIGPYTHON %feature( "kwargs" ) ContourGenerate; +#elif defined(SWIGCSHARP) +%apply bool {int useNoData}; #endif %apply Pointer NONNULL {GDALRasterBandShadow *srcBand, OGRLayerShadow* dstLayer}; %apply (int nList, double *pList ) { (int fixedLevelCount, double *fixedLevels ) }; @@ -687,11 +726,7 @@ GDALDatasetShadow *AutoCreateWarpedVRT( GDALDatasetShadow *src_ds, /************************************************************************/ %newobject CreatePansharpenedVRT; -#ifndef SWIGCSHARP %apply (int object_list_count, GDALRasterBandShadow **poObjects) {(int nInputSpectralBands, GDALRasterBandShadow **ahInputSpectralBands)}; -#else -%apply GDALRasterBandShadow OBJPTRS_STATIC[] {GDALRasterBandShadow** ahInputSpectralBands} -#endif /* SWIGCSHARP */ %apply Pointer NONNULL { GDALRasterBandShadow* panchroBand }; %inline %{ @@ -773,9 +808,26 @@ public: } #ifdef SWIGCSHARP - %apply (double *inout) {(double*)}; - %apply (double *inout) {(int*)}; -#endif +%apply (int nList, double *pList) { (int x, double *pX), (int y, double *pY), (int z, double *pZ) }; +%apply (int nList, int *pList) { (int success, int *panSuccess) }; + bool TransformPoints( int bDstToSrc, + int x, double *pX, int y, double *pY, int z, double *pZ, + int success, int *panSuccess ) { + CPLErrorReset(); + if (!pX || !pY || !pZ || !panSuccess) { + CPLError(CE_Failure, CPLE_IllegalArg, "All arrays must be non-null."); + return 0; + } + else if (x != y || x != z || x != success) { + CPLError(CE_Failure, CPLE_IllegalArg, "All arrays must be the same size."); + return 0; + } + + return GDALUseTransformer( self, bDstToSrc, x, pX, pY, pZ, panSuccess ); + } +%clear (int x, double *pX), (int y, double *pY), (int z, double *pZ); +%clear (int success, int *panSuccess); +#else int TransformPoints( int bDstToSrc, int nCount, double *x, double *y, double *z, int *panSuccess ) { @@ -785,9 +837,6 @@ public: return nRet; } -#ifdef SWIGCSHARP - %clear (double*); - %clear (int*); #endif /************************************************************************/ diff --git a/swig/include/RasterAttributeTable.i b/swig/include/RasterAttributeTable.i index 63f66c8d9d59..86ec104b15f5 100644 --- a/swig/include/RasterAttributeTable.i +++ b/swig/include/RasterAttributeTable.i @@ -61,10 +61,14 @@ typedef enum { } GDALRATTableType; #endif /* CSHARP */ +%{ +#include "gdal.h" +%} %rename (RATDateTime) GDALRATDateTime; -typedef struct -{ +struct GDALRATDateTime { + +%mutable; /*! Year */ int nYear; /*! Month [1, 12] */ int nMonth; /*! Day [1, 31] */ int nDay; @@ -75,7 +79,35 @@ typedef struct /*! Time zone minute: 0, 15, 30, 45 */ int nTimeZoneMinute; /*! Whether time zone is positive (or null) */ bool bPositiveTimeZone; /*! Whether this object is valid */ bool bIsValid; -} GDALRATDateTime; + +%extend { + GDALRATDateTime( int year, int month, int day, int hour, int minute, float second, int timeZoneHour, int timeZoneMinute, bool positiveTimeZone ) { + GDALRATDateTime *self = (GDALRATDateTime*) CPLMalloc( sizeof( GDALRATDateTime ) ); + self->nYear = year; + self->nMonth = month; + self->nDay = day; + self->nHour = hour; + self->nMinute = minute; + self->fSecond = second; + self->nTimeZoneHour = timeZoneHour; + self->nTimeZoneMinute = timeZoneMinute; + self->bPositiveTimeZone = positiveTimeZone; + self->bIsValid = TRUE; + return self; + } + GDALRATDateTime() { + GDALRATDateTime *self = (GDALRATDateTime*) CPLMalloc( sizeof( GDALRATDateTime ) ); + self->nYear = self->nMonth = self->nDay = self->nHour = self->nMinute = self->nTimeZoneHour = self->nTimeZoneMinute = 0; + self->fSecond = 0.0; + self->bPositiveTimeZone = self->bIsValid = FALSE; + return self; + } + + ~GDALRATDateTime() { + CPLFree(self); + } +} //%extend +}; %rename (RasterAttributeTable) GDALRasterAttributeTableShadow; diff --git a/swig/include/cpl.i b/swig/include/cpl.i index 709f6739ae6b..351fdabd62a6 100644 --- a/swig/include/cpl.i +++ b/swig/include/cpl.i @@ -895,23 +895,43 @@ int wrapper_VSIStatL( const char * path, StatBuf *psStatBufOut, int nFlags = 0 ) #endif -%rename (GetFileMetadata) VSIGetFileMetadata; +%rename("%(regex:/.*VSIGetFileMetadata/GetFileMetadata/)s") ""; #if defined(SWIGPYTHON) || defined(SWIGCSHARP) %apply (char **dictAndCSLDestroy) { char ** }; #else %apply (char **) { char ** }; #endif %apply (char **options) { char ** options }; +#if defined(SWIGPYTHON) char** VSIGetFileMetadata( const char *path, const char* domain, char** options = NULL ); +#else +%inline { + char** wrapper_VSIGetFileMetadata( const char *path, const char* domain, + char** options = NULL ) { + return VSIGetFileMetadata(path, domain, options); + } +} +#endif %clear char **; -%rename (SetFileMetadata) VSISetFileMetadata; +%rename("%(regex:/.*VSISetFileMetadata/SetFileMetadata/)s") ""; %apply (char **dict) { char ** metadata }; +#if defined(SWIGPYTHON) bool VSISetFileMetadata( const char * path, char** metadata, const char* domain, char** options = NULL ); +#else +%inline { + bool wrapper_VSISetFileMetadata( const char * path, + char** metadata, + const char* domain, + char** options = NULL ) { + return VSISetFileMetadata(path, metadata, domain, options); + } +} +#endif %clear char **; %apply Pointer NONNULL {VSILFILE* fp}; @@ -1035,7 +1055,16 @@ int VSIFWriteL( const char *pBuffer, int nSize, int nCount, VSILFILE *fp ); const char* CPLReadLineL(VSILFILE* fp); void VSINetworkStatsReset(); +#if defined(SWIGPYTHON) retStringAndCPLFree* VSINetworkStatsGetAsSerializedJSON( char** options = NULL ); +#else +%rename (NetworkStatsGetAsSerializedJSON) wrapper_VSINetworkStatsGetAsSerializedJSON; +%inline { +retStringAndCPLFree* wrapper_VSINetworkStatsGetAsSerializedJSON( char** options = NULL ) { + return VSINetworkStatsGetAsSerializedJSON(options); + } +} +#endif #endif /* !defined(SWIGJAVA) */ diff --git a/swig/include/csharp/csharp_strings.i b/swig/include/csharp/csharp_strings.i index c27849299c53..51787cc35a51 100644 --- a/swig/include/csharp/csharp_strings.i +++ b/swig/include/csharp/csharp_strings.i @@ -211,6 +211,20 @@ SWIGEXPORT void SWIGSTDCALL RegisterUtf8StringCallback_$module(CSharpUtf8StringH } _ar[ar.Length] = IntPtr.Zero; } + public StringListMarshal(System.Collections.Generic.ICollection> kvps) + : this(KvpCollectionToStringArray(kvps)) {} + + private static string[] KvpCollectionToStringArray(System.Collections.Generic.ICollection> kvps) { + string[] array = new string[2 * kvps.Count]; + int i = 0; + foreach (var kvp in kvps) { + array[2 * i] = kvp.Key; + array[2 * i + 1] = kvp.Value; + i++; + } + return array; + } + ~StringListMarshal() => Dispose(); public virtual void Dispose() { var handles = System.Threading.Interlocked.Exchange(ref _handles, null); @@ -236,6 +250,22 @@ SWIGEXPORT void SWIGSTDCALL RegisterUtf8StringCallback_$module(CSharpUtf8StringH } return ret; } + public static System.Collections.Generic.KeyValuePair[] DecodeKeyValuePairArray(IntPtr pKvp) { + int count = 0; + if (pKvp != IntPtr.Zero) checked { + while (System.Runtime.InteropServices.Marshal.ReadIntPtr(pKvp, 2 * count * IntPtr.Size) != IntPtr.Zero) + count++; + } + var ret = new System.Collections.Generic.KeyValuePair[count]; + for(int cx = 0; cx < count; cx++) { + IntPtr pKey = System.Runtime.InteropServices.Marshal.ReadIntPtr(pKvp, 2 * cx * IntPtr.Size); + IntPtr pValue = System.Runtime.InteropServices.Marshal.ReadIntPtr(pKvp, (2 * cx + 1) * IntPtr.Size); + string key = $module.StringEncoder?.FromNullTerminated(pKey); + string value = $module.StringEncoder?.FromNullTerminated(pValue); + ret[cx] = new System.Collections.Generic.KeyValuePair(key, value); + } + return ret; + } } %} diff --git a/swig/include/csharp/gdal_csharp.i b/swig/include/csharp/gdal_csharp.i index 6be3896d2222..761f09683bbe 100644 --- a/swig/include/csharp/gdal_csharp.i +++ b/swig/include/csharp/gdal_csharp.i @@ -28,78 +28,48 @@ DEFINE_EXTERNAL_CLASS(GDALSubdatasetInfoShadow, OSGeo.GDAL.SubdatasetInfo) %apply (double *OUTPUT) {double *min_ret, double *max_ret}; %apply (int *nLen) {int *buckets_ret}; %apply (double *pList) {double *burn_values_list, double *fixedLevels}; -%apply (int **pList) {int **ppanHistogram}; %apply (void *buffer_ptr) {void *pfnTransformer, void *pTransformArg}; -%apply (void *buffer_ptr) {GDAL_GCP const *pGCPs}; -%csmethodmodifiers __SetGCPs "private"; -%csmethodmodifiers __GetGCPs "private"; -%csmethodmodifiers GDALGCPsToGeoTransform "private"; +VALUE_LIST_INOUT(GDAL_GCP, GCP) +%apply (int nList, GDAL_GCP *pList) { (int nGCPs, GDAL_GCP const *pGCPs) }; +%apply (int* nList, GDAL_GCP **pList) { (int *nGCPs, GDAL_GCP const **pGCPs) }; -%apply (void *buffer_ptr) {GDALDatasetShadow** poObjects}; -%csmethodmodifiers wrapper_GDALWarpDestDS "private"; -%csmethodmodifiers wrapper_GDALWarpDestName "private"; - -%apply (GDALProgressFunc callback) {GDALProgressFunc pfnProgress}; %apply (void *buffer_ptr) {void *pProgressData}; +%typemap(cscode, noblock=1) GDALRasterIOExtraArg %{ + private $module.GDALProgressFuncDelegate pfnProgressManaged; + public void SetProgressDelegate(Func progressFunc, IntPtr progressData = default(IntPtr)) { + pProgressData = progressData; + pfnProgress = pfnProgressManaged = progressFunc == null ? default($module.GDALProgressFuncDelegate) + : (p, m, d) => progressFunc(p, $module.StringEncoder?.FromNullTerminated(m), d) ? 1 : 0; + } + public void SetProgressDelegate(Func progressFunc, TData progressData) { + pfnProgress = pfnProgressManaged = progressFunc == null ? default($module.GDALProgressFuncDelegate) + : (p, m, _) => progressFunc(p, $module.StringEncoder?.FromNullTerminated(m), progressData) ? 1 : 0; + } +%} %rename (RasterIOExtraArg) GDALRasterIOExtraArg; -typedef struct +struct GDALRasterIOExtraArg { - /*! Version of structure (to allow future extensions of the structure) */ - int nVersion; - - /*! Resampling algorithm */ - GDALRIOResampleAlg eResampleAlg; - - /*! Progress callback */ - GDALProgressFunc pfnProgress; - /*! Progress callback user data */ - void *pProgressData; - - /*! Indicate if dfXOff, dfYOff, dfXSize and dfYSize are set. - Mostly reserved from the VRT driver to communicate a more precise - source window. Must be such that dfXOff - nXOff < 1.0 and - dfYOff - nYOff < 1.0 and nXSize - dfXSize < 1.0 and nYSize - dfYSize < 1.0 */ - int bFloatingPointWindowValidity; - /*! Pixel offset to the top left corner. Only valid if bFloatingPointWindowValidity = TRUE */ - double dfXOff; - /*! Line offset to the top left corner. Only valid if bFloatingPointWindowValidity = TRUE */ - double dfYOff; - /*! Width in pixels of the area of interest. Only valid if bFloatingPointWindowValidity = TRUE */ - double dfXSize; - /*! Height in pixels of the area of interest. Only valid if bFloatingPointWindowValidity = TRUE */ - double dfYSize; -} GDALRasterIOExtraArg; + %mutable; + int nVersion; + GDALRIOResampleAlg eResampleAlg; + GDALProgressFunc pfnProgress; + void *pProgressData; + int bFloatingPointWindowValidity; + double dfXOff; + double dfYOff; + double dfXSize; + double dfYSize; +}; DEFINE_EXTERNAL_CLASS(OGRLayerShadow, OSGeo.OGR.Layer) DEFINE_EXTERNAL_CLASS(OGRFeatureShadow, OSGeo.OGR.Feature) %define %rasterio_functions(GDALTYPE,CSTYPE) - public CPLErr ReadRaster(int xOff, int yOff, int xSize, int ySize, CSTYPE[] buffer, int buf_xSize, int buf_ySize, int pixelSpace, int lineSpace) { - CPLErr retval; - GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); - try { - retval = ReadRaster(xOff, yOff, xSize, ySize, handle.AddrOfPinnedObject(), buf_xSize, buf_ySize, GDALTYPE, pixelSpace, lineSpace); - } finally { - handle.Free(); - } - GC.KeepAlive(this); - return retval; - } - public CPLErr WriteRaster(int xOff, int yOff, int xSize, int ySize, CSTYPE[] buffer, int buf_xSize, int buf_ySize, int pixelSpace, int lineSpace) { - CPLErr retval; - GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); - try { - retval = WriteRaster(xOff, yOff, xSize, ySize, handle.AddrOfPinnedObject(), buf_xSize, buf_ySize, GDALTYPE, pixelSpace, lineSpace); - } finally { - handle.Free(); - } - GC.KeepAlive(this); - return retval; - } - public CPLErr ReadRaster(int xOff, int yOff, int xSize, int ySize, CSTYPE[] buffer, int buf_xSize, int buf_ySize, int pixelSpace, int lineSpace, RasterIOExtraArg extraArg) { + public CPLErr ReadRaster(int xOff, int yOff, int xSize, int ySize, CSTYPE[] buffer, int buf_xSize, int buf_ySize, + long pixelSpace = 0, long lineSpace = 0, RasterIOExtraArg extraArg = null) { CPLErr retval; GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { @@ -110,7 +80,8 @@ DEFINE_EXTERNAL_CLASS(OGRFeatureShadow, OSGeo.OGR.Feature) GC.KeepAlive(this); return retval; } - public CPLErr WriteRaster(int xOff, int yOff, int xSize, int ySize, CSTYPE[] buffer, int buf_xSize, int buf_ySize, int pixelSpace, int lineSpace, RasterIOExtraArg extraArg) { + public CPLErr WriteRaster(int xOff, int yOff, int xSize, int ySize, CSTYPE[] buffer, int buf_xSize, int buf_ySize, + long pixelSpace = 0, long lineSpace = 0, RasterIOExtraArg extraArg = null) { CPLErr retval; GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { @@ -125,11 +96,45 @@ DEFINE_EXTERNAL_CLASS(OGRFeatureShadow, OSGeo.OGR.Feature) %enddef %typemap(cscode, noblock="1") GDALRasterBandShadow { -/*! Eight bit unsigned integer */ %rasterio_functions(DataType.GDT_Byte,byte) -/*! Sixteen bit signed integer */ %rasterio_functions(DataType.GDT_Int16,short) -/*! Thirty two bit signed integer */ %rasterio_functions(DataType.GDT_Int32,int) -/*! Thirty two bit floating point */ %rasterio_functions(DataType.GDT_Float32,float) -/*! Sixty four bit floating point */ %rasterio_functions(DataType.GDT_Float64,double) +/*! 8-bit unsigned integer */ %rasterio_functions(DataType.GDT_Byte, byte) +/*! 16-bit signed integer */ %rasterio_functions(DataType.GDT_Int16, short) +/*! 32-bit signed integer */ %rasterio_functions(DataType.GDT_Int32, int) +/*! 64-bit signed integer */ %rasterio_functions(DataType.GDT_Int64, long) +/*! 32-bit floating point */ %rasterio_functions(DataType.GDT_Float32, float) +/*! 64-bit floating point */ %rasterio_functions(DataType.GDT_Float64, double) +/*! 16-bit unsigned integer */ %rasterio_functions(DataType.GDT_UInt16, ushort) +/*! 32-bit unsigned integer */ %rasterio_functions(DataType.GDT_UInt32, uint) +/*! 64-bit unsigned integer */ %rasterio_functions(DataType.GDT_UInt64, ulong) +/*! 8-bit signed integer */ %rasterio_functions(DataType.GDT_Int8, sbyte) + + +/* + * Overloads to maintain backwards compatibility with multi-argument typemaps + */ + +[Obsolete("Use MaximumOfNBands(Band[] band_count) instead.")] +public static ComputedBand MaximumOfNBands(int band_count, Band[] bands) => MaximumOfNBands(bands); +[Obsolete("Use MeanOfNBands(Band[] band_count) instead.")] +public static ComputedBand MeanOfNBands(int band_count, Band[] bands) => MeanOfNBands(bands); +[Obsolete("Use MinimumOfNBands(Band[] band_count) instead.")] +public static ComputedBand MinimumOfNBands(int band_count, Band[] bands) => MinimumOfNBands(bands); +[Obsolete("Use GetHistogram(double min, double max, int[] histogram, bool include_out_of_range, bool approx_ok, Gdal.GDALProgressFuncDelegate callback, string callback_data) instead.")] +public CPLErr GetHistogram(double min, double max, int buckets, int[] panHistogram, int include_out_of_range, int approx_ok, Gdal.GDALProgressFuncDelegate callback, string callback_data) + => GetHistogram(min, max, panHistogram, include_out_of_range != 0, approx_ok != 0, callback, callback_data); +[Obsolete("Use AdviseRead(int xoff, int yoff, int xsize, int ysize, int buf_xsize, int buf_ysize, DataType buf_type, string[] options) instead.")] +public CPLErr AdviseRead(int xoff, int yoff, int xsize, int ysize, ref int buf_xsize, ref int buf_ysize, ref int buf_type, string[] options) + => AdviseRead(xoff, yoff, xsize, ysize, buf_xsize, buf_ysize, (DataType)buf_type, options); +[Obsolete("Use public int Checksum(int xoff, int yoff, int xsize, int ysize) instead.")] +public int Checksum(int xoff, int yoff, ref int xsize, ref int ysize) => Checksum(xoff, yoff, xsize, ysize); +[Obsolete("Use SetDefaultHistogram(double min, double max, int[] buckets_in) instead.")] +public CPLErr SetDefaultHistogram(double min, double max, int buckets_in, int[] panHistogram_in) + => SetDefaultHistogram(min, max, panHistogram_in); +[Obsolete("Use GetDefaultHistogram(out double min_ret, out double max_ret, out int[] histogram, bool force, Gdal.GDALProgressFuncDelegate callback, string callback_data) instead.")] +public CPLErr GetDefaultHistogram(out double min_ret, out double max_ret, out int buckets_ret, out int[] ppanHistogram, int force, Gdal.GDALProgressFuncDelegate callback, string callback_data) { + var ret = GetDefaultHistogram(out min_ret, out max_ret, out ppanHistogram, force != 0, callback, callback_data); + buckets_ret = ppanHistogram.Length; + return ret; +} } /*! Sixteen bit unsigned integer */ //%rasterio_functions(DataType.GDT_UInt16,ushort) @@ -140,34 +145,10 @@ DEFINE_EXTERNAL_CLASS(OGRFeatureShadow, OSGeo.OGR.Feature) /*! Complex Float64 */ //%rasterio_functions(DataType.GDT_CFloat64,int) %define %ds_rasterio_functions(GDALTYPE,CSTYPE) - public CPLErr ReadRaster(int xOff, int yOff, int xSize, int ySize, CSTYPE[] buffer, int buf_xSize, int buf_ySize, - int bandCount, int[] bandMap, int pixelSpace, int lineSpace, int bandSpace) { - CPLErr retval; - GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); - try { - retval = ReadRaster(xOff, yOff, xSize, ySize, handle.AddrOfPinnedObject(), buf_xSize, buf_ySize, GDALTYPE, - bandCount, bandMap, pixelSpace, lineSpace, bandSpace); - } finally { - handle.Free(); - } - GC.KeepAlive(this); - return retval; - } - public CPLErr WriteRaster(int xOff, int yOff, int xSize, int ySize, CSTYPE[] buffer, int buf_xSize, int buf_ySize, - int bandCount, int[] bandMap, int pixelSpace, int lineSpace, int bandSpace) { - CPLErr retval; - GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); - try { - retval = WriteRaster(xOff, yOff, xSize, ySize, handle.AddrOfPinnedObject(), buf_xSize, buf_ySize, GDALTYPE, - bandCount, bandMap, pixelSpace, lineSpace, bandSpace); - } finally { - handle.Free(); - } - GC.KeepAlive(this); - return retval; - } public CPLErr ReadRaster(int xOff, int yOff, int xSize, int ySize, CSTYPE[] buffer, int buf_xSize, int buf_ySize, - int bandCount, int[] bandMap, int pixelSpace, int lineSpace, int bandSpace, RasterIOExtraArg extraArg) { + int bandCount, int[] bandMap = null, long pixelSpace = 0, long lineSpace = 0, long bandSpace = 0, RasterIOExtraArg extraArg = null) { + if (bandMap != null && bandMap.Length < bandCount) + throw new ArgumentException("Array bandMap must be at least bandCount elements long."); CPLErr retval; GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { @@ -180,7 +161,9 @@ DEFINE_EXTERNAL_CLASS(OGRFeatureShadow, OSGeo.OGR.Feature) return retval; } public CPLErr WriteRaster(int xOff, int yOff, int xSize, int ySize, CSTYPE[] buffer, int buf_xSize, int buf_ySize, - int bandCount, int[] bandMap, int pixelSpace, int lineSpace, int bandSpace, RasterIOExtraArg extraArg) { + int bandCount, int[] bandMap = null, long pixelSpace = 0, long lineSpace = 0, long bandSpace = 0, RasterIOExtraArg extraArg = null) { + if (bandMap != null && bandMap.Length < bandCount) + throw new ArgumentException("Array bandMap must be at least bandCount elements long."); CPLErr retval; GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { @@ -195,73 +178,50 @@ DEFINE_EXTERNAL_CLASS(OGRFeatureShadow, OSGeo.OGR.Feature) %enddef +%csmethodmodifiers GetGCPs "private"; +%typemap(csimports) GDALDatasetShadow %{ + using System; + using System.Runtime.InteropServices; + using OSGeo.OGR; +%} %typemap(cscode, noblock="1") GDALDatasetShadow { -/*! Eight bit unsigned integer */ %ds_rasterio_functions(DataType.GDT_Byte,byte) -/*! Sixteen bit signed integer */ %ds_rasterio_functions(DataType.GDT_Int16,short) -/*! Thirty two bit signed integer */ %ds_rasterio_functions(DataType.GDT_Int32,int) -/*! Thirty two bit floating point */ %ds_rasterio_functions(DataType.GDT_Float32,float) -/*! Sixty four bit floating point */ %ds_rasterio_functions(DataType.GDT_Float64,double) - -public int BuildOverviews( string resampling, int[] overviewlist, $module.GDALProgressFuncDelegate callback, string callback_data, string[] options) { - int retval; - if (overviewlist.Length <= 0) - throw new ArgumentException("overviewlist size is small (BuildOverviews)"); - - IntPtr ptr = Marshal.AllocHGlobal(overviewlist.Length * Marshal.SizeOf(overviewlist[0])); - try { - Marshal.Copy(overviewlist, 0, ptr, overviewlist.Length); - retval = BuildOverviews(resampling, overviewlist.Length, ptr, callback, callback_data, options); - } finally { - Marshal.FreeHGlobal(ptr); - } - GC.KeepAlive(this); - return retval; - } +/*! 8-bit unsigned integer */ %ds_rasterio_functions(DataType.GDT_Byte, byte) +/*! 16-bit signed integer */ %ds_rasterio_functions(DataType.GDT_Int16, short) +/*! 32-bit signed integer */ %ds_rasterio_functions(DataType.GDT_Int32, int) +/*! 64-bit signed integer */ %ds_rasterio_functions(DataType.GDT_Int64, long) +/*! 32-bit floating point */ %ds_rasterio_functions(DataType.GDT_Float32, float) +/*! 64-bit floating point */ %ds_rasterio_functions(DataType.GDT_Float64, double) +/*! 16-bit unsigned integer */ %ds_rasterio_functions(DataType.GDT_UInt16, ushort) +/*! 32-bit unsigned integer */ %ds_rasterio_functions(DataType.GDT_UInt32, uint) +/*! 64-bit unsigned integer */ %ds_rasterio_functions(DataType.GDT_UInt64, ulong) +/*! 8-bit signed integer */ %ds_rasterio_functions(DataType.GDT_Int8, sbyte) -public int BuildOverviews( string resampling, int[] overviewlist, $module.GDALProgressFuncDelegate callback, string callback_data) { - return BuildOverviews( resampling, overviewlist, null, null, null); +public GCP[] GetGCPs() { + GetGCPs(out GCP[] gcps); + return gcps; } -public int BuildOverviews( string resampling, int[] overviewlist) { - return BuildOverviews( resampling, overviewlist, null, null); +/* + * Overloads to maintain backwards compatibility with multi-argument typemaps + */ + + [Obsolete("Use AdviseRead(int xoff, int yoff, int xsize, int ysize, ref int buf_xsize, ref int buf_ysize, ref int buf_type, int[] band_list, string[] options) instead.")] + public CPLErr AdviseRead(int xoff, int yoff, int xsize, int ysize, ref int buf_xsize, ref int buf_ysize, ref int buf_type, int band_list, int[] pband_list, string[] options) + => AdviseRead(xoff, yoff, xsize, ysize, buf_xsize, buf_ysize, (DataType)buf_type, pband_list, options); + + [Obsolete("Use BuildOverviews(string resampling, int[] overviewlist, Gdal.GDALProgressFuncDelegate callback, string callback_data, string[] options) instead.")] + public int BuildOverviews(string resampling, int overviewlist, IntPtr pOverviews, Gdal.GDALProgressFuncDelegate callback, string callback_data, string[] options) { + var managedList = new int[overviewlist]; + Marshal.Copy(pOverviews, managedList, overviewlist, overviewlist); + return BuildOverviews(resampling, managedList, callback, callback_data, options); } -public GCP[] GetGCPs() { - /*hello*/ - IntPtr cPtr = __GetGCPs(); - int length = GetGCPCount(); - GCP[] ret = null; - if (cPtr != IntPtr.Zero && length > 0) - { - ret = new GCP[length]; - for (int i=0; i < length; i++) - ret[i] = __ReadCArrayItem_GDAL_GCP(cPtr, i); - } - GC.KeepAlive(this); - return ret; - } - -public CPLErr SetGCPs(GCP[] pGCPs, string pszGCPProjection) { - CPLErr ret = 0; - if (pGCPs != null && pGCPs.Length > 0) - { - IntPtr cPtr = __AllocCArray_GDAL_GCP(pGCPs.Length); - if (cPtr == IntPtr.Zero) - throw new ApplicationException("Error allocating CArray with __AllocCArray_GDAL_GCP"); - - try { - for (int i=0; i < pGCPs.Length; i++) - __WriteCArrayItem_GDAL_GCP(cPtr, i, pGCPs[i]); - - ret = __SetGCPs(pGCPs.Length, cPtr, pszGCPProjection); - } - finally - { - __FreeCArray_GDAL_GCP(cPtr); - } - } - GC.KeepAlive(this); - return ret; + [Obsolete("Use GetNextFeature(out Layer ppoBelongingLayer, out double pdfProgressPct, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public Feature GetNextFeature(ref IntPtr ppoBelongingLayer, ref double pdfProgressPct, Gdal.GDALProgressFuncDelegate callback, string callback_data) { + Feature feature = GetNextFeature(out Layer belongingLayer, out double progressPct, callback, callback_data); + ppoBelongingLayer = Layer.getCPtr(belongingLayer).Handle; + pdfProgressPct = progressPct; + return feature; } } @@ -273,27 +233,6 @@ public CPLErr SetGCPs(GCP[] pGCPs, string pszGCPProjection) { /*! Complex Float64 */ //%ds_rasterio_functions(DataType.GDT_CFloat64,int) %pragma(csharp) modulecode=%{ - public static int GCPsToGeoTransform(GCP[] pGCPs, double[] argout, int bApproxOK) { - int ret = 0; - if (pGCPs != null && pGCPs.Length > 0) - { - IntPtr cPtr = __AllocCArray_GDAL_GCP(pGCPs.Length); - if (cPtr == IntPtr.Zero) - throw new ApplicationException("Error allocating CArray with __AllocCArray_GDAL_GCP"); - - try { - for (int i=0; i < pGCPs.Length; i++) - __WriteCArrayItem_GDAL_GCP(cPtr, i, pGCPs[i]); - - ret = GCPsToGeoTransform(pGCPs.Length, cPtr, argout, bApproxOK); - } - finally - { - __FreeCArray_GDAL_GCP(cPtr); - } - } - return ret; - } /* * Keep this seemingly redundant overload to maintain @@ -375,82 +314,6 @@ public CPLErr SetGCPs(GCP[] pGCPs, string pszGCPProjection) { } } - public static int Warp(Dataset dstDS, Dataset[] poObjects, GDALWarpAppOptions warpAppOptions, $module.GDALProgressFuncDelegate callback, string callback_data) { - int retval = 0; - if (poObjects.Length <= 0) - throw new ArgumentException("poObjects size is small (GDALWarpDestDS)"); - - int intPtrSize = Marshal.SizeOf(typeof(IntPtr)); - IntPtr nativeArray = Marshal.AllocHGlobal(poObjects.Length * intPtrSize); - try { - for (int i=0; i < poObjects.Length; i++) - Marshal.WriteIntPtr(nativeArray, i * intPtrSize, Dataset.getCPtr(poObjects[i]).Handle); - - retval = wrapper_GDALWarpDestDS(dstDS, poObjects.Length, nativeArray, warpAppOptions, callback, callback_data); - } finally { - Marshal.FreeHGlobal(nativeArray); - } - return retval; - } - - public static Dataset Warp(string dest, Dataset[] poObjects, GDALWarpAppOptions warpAppOptions, $module.GDALProgressFuncDelegate callback, string callback_data) { - Dataset retval = null; - if (poObjects.Length <= 0) - throw new ArgumentException("poObjects size is small (GDALWarpDestDS)"); - - int intPtrSize = Marshal.SizeOf(typeof(IntPtr)); - IntPtr nativeArray = Marshal.AllocHGlobal(poObjects.Length * intPtrSize); - try { - for (int i=0; i < poObjects.Length; i++) - Marshal.WriteIntPtr(nativeArray, i * intPtrSize, Dataset.getCPtr(poObjects[i]).Handle); - - retval = wrapper_GDALWarpDestName(dest, poObjects.Length, nativeArray, warpAppOptions, callback, callback_data); - } finally { - Marshal.FreeHGlobal(nativeArray); - } - return retval; - } - - public static Dataset BuildVRT(string dest, string[] poObjects, GDALBuildVRTOptions buildVrtAppOptions, $module.GDALProgressFuncDelegate callback, string callback_data) { - return wrapper_GDALBuildVRT_names(dest, poObjects, buildVrtAppOptions, callback, callback_data); - } - - public static Dataset BuildVRT(string dest, Dataset[] poObjects, GDALBuildVRTOptions buildVrtAppOptions, $module.GDALProgressFuncDelegate callback, string callback_data) { - Dataset retval = null; - if (poObjects.Length <= 0) - throw new ArgumentException("poObjects size is small (BuildVRT)"); - - int intPtrSize = Marshal.SizeOf(typeof(IntPtr)); - IntPtr nativeArray = Marshal.AllocHGlobal(poObjects.Length * intPtrSize); - try { - for (int i=0; i < poObjects.Length; i++) - Marshal.WriteIntPtr(nativeArray, i * intPtrSize, Dataset.getCPtr(poObjects[i]).Handle); - - retval = wrapper_GDALBuildVRT_objects(dest, poObjects.Length, nativeArray, buildVrtAppOptions, callback, callback_data); - } finally { - Marshal.FreeHGlobal(nativeArray); - } - return retval; - } - - public static Dataset MultiDimTranslate(string dest, Dataset[] poObjects, GDALMultiDimTranslateOptions multiDimAppOptions, $module.GDALProgressFuncDelegate callback, string callback_data) { - Dataset retval = null; - if (poObjects.Length <= 0) - throw new ArgumentException("poObjects size is small (GDALMultiDimTranslateDestName)"); - - int intPtrSize = Marshal.SizeOf(typeof(IntPtr)); - IntPtr nativeArray = Marshal.AllocHGlobal(poObjects.Length * intPtrSize); - try { - for (int i=0; i < poObjects.Length; i++) - Marshal.WriteIntPtr(nativeArray, i * intPtrSize, Dataset.getCPtr(poObjects[i]).Handle); - - retval = wrapper_GDALMultiDimTranslateDestName(dest, poObjects.Length, nativeArray, multiDimAppOptions, callback, callback_data); - } finally { - Marshal.FreeHGlobal(nativeArray); - } - return retval; - } - public static bool VSIFSeekL(IntPtr fp, long offset, System.IO.SeekOrigin origin) { return VSIFSeekL(fp, offset, (int)origin) == 0; } @@ -487,6 +350,10 @@ public CPLErr SetGCPs(GCP[] pGCPs, string pszGCPProjection) { handle.Free(); } } + public static Dataset[] GetOpenDatasets() { + wrapper_GetOpenDatasets(out Dataset[] datasets); + return datasets; + } %} %rename (GetMemFileBuffer) wrapper_VSIGetMemFileBuffer; @@ -517,3 +384,371 @@ GByte* wrapper_VSIGetMemFileBuffer(const char *utf8_string, vsi_l_offset *pnData SWIG_CSharpSetPendingExceptionArgument(static_cast(code), message, param_name); } %} + + +%typemap(cscode, noblock="1") GDALGroupHS { + [Obsolete("Use CreateAttribute(string name, ulong[] dimensions, ExtendedDataType data_type, string[] options) instead.", error: true)] + public Attribute CreateAttribute(string name, int dimensions, uint[] sizes, ExtendedDataType data_type, string[] options) + => throw new NotSupportedException(); +} + +%typemap(cscode, noblock="1") GDALAlgorithmArgHS { + [Obsolete("Use SetAsIntegerList(int[] nList) instead.")] + public bool SetAsIntegerList(int nList, int[] pList) => SetAsIntegerList(pList); + [Obsolete("Use SetAsDoubleList(double[] nList) instead.")] + public bool SetAsDoubleList(int nList, double[] pList) => SetAsDoubleList(pList); +} + +%typemap(cscode, noblock="1") GDALTransformerInfoShadow { + [Obsolete("Use TransformPoints(int bDstToSrc, double[] x, double[] y, double[] z, int[] success) instead.", error: true)] + public int TransformPoints(int bDstToSrc, int nCount, double[] x, double[] y, double[] z, double[] panSuccess) + => throw new NotSupportedException(); +} + +%typemap(cscode, noblock="1") GDALMDArrayHS { + [Obsolete("Use CreateAttribute(string name, ulong[] dimensions, ExtendedDataType data_type, string[] options) instead.", error: true)] + public Attribute CreateAttribute(string name, int dimensions, uint[] sizes, ExtendedDataType data_type, string[] options) + => throw new NotSupportedException(); + + [Obsolete("Use Resize(ulong[] newDimensions, string[] options) instead.", error: true)] + public CPLErr Resize(int newDimensions, uint[] newSizes, string[] options) => throw new NotSupportedException(); + + [Obsolete("Use Transpose(int[] axisMap) instead.")] + public MDArray Transpose(int axisMap, int[] mapInts) => Transpose(mapInts); +} + + +%typemap(cscode, noblock="1") GDALRATDateTime { + + public static implicit operator RATDateTime(DateTimeOffset value) => FromDateTimeOffset(value); + public static implicit operator DateTimeOffset(RATDateTime value) => value.ToDateTimeOffset(); + public DateTimeOffset ToDateTimeOffset() { + var sec = (int)fSecond; + var ms = (int)Math.Round((fSecond - sec) * 1000); + var offsetMins = nTimeZoneHour * 60 + nTimeZoneMinute; + if (!bPositiveTimeZone) + offsetMins *= -1; + var offset = TimeSpan.FromMinutes(offsetMins); + return new DateTimeOffset(nYear, nMonth, nDay, nHour, nMinute, sec, ms, offset); + } + public static RATDateTime FromDateTimeOffset(DateTimeOffset value) => new RATDateTime( + value.Year, value.Month, value.Day, + value.Hour, value.Minute, value.Second + value.Millisecond / 1000f, + Math.Abs(value.Offset.Hours), Math.Abs(value.Offset.Minutes), value.Offset.Ticks >= 0 + ); +} + +/* + * Overloads to maintain backwards compatibility with multi-argument typemaps + */ + +%pragma(csharp) modulecode=%{ + [Obsolete("Use GCPsToHomography(GCP[] nGCPs, double[] argout) instead.", error: true)] + public static int GCPsToHomography(int nGCPs, IntPtr pGCPs, double[] argout) + => throw new NotSupportedException(); + + [Obsolete("Use RasterizeLayers(Dataset dataset, int[] bands, Layer[] layers, GDALTransformerFuncDelegate pfnTransformer, IntPtr pTransformArg, double[] burn_values, string[] options, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public static int RasterizeLayer(Dataset dataset, int bands, int[] band_list, OSGeo.OGR.Layer layer, IntPtr pfnTransformer, IntPtr pTransformArg, int burn_values, double[] burn_values_list, string[] options, GDALProgressFuncDelegate callback, string callback_data) + => RasterizeLayers(dataset, band_list, new OSGeo.OGR.Layer[]{ layer }, Marshal.GetDelegateForFunctionPointer(pfnTransformer), pTransformArg, burn_values_list, options, callback, callback_data); + + [Obsolete("Use RegenerateOverviews(Band srcBand, Band[] overviewBandCount, string resampling, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public static int RegenerateOverviews(Band srcBand, int overviewBandCount, Band[] overviewBands, string resampling, GDALProgressFuncDelegate callback, string callback_data) + => RegenerateOverviews(srcBand, overviewBands, resampling, callback, callback_data); + + [Obsolete("Use ContourGenerate(Band srcBand, double contourInterval, double contourBase, double[] fixedLevelCount, bool useNoData, double noDataValue, Layer dstLayer, int idField, int elevField, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public static int ContourGenerate(Band srcBand, double contourInterval, double contourBase, int fixedLevelCount, double[] fixedLevels, int useNoData, double noDataValue, OSGeo.OGR.Layer dstLayer, int idField, int elevField, GDALProgressFuncDelegate callback, string callback_data) + => ContourGenerate(srcBand, contourInterval, contourBase, fixedLevels, useNoData != 0, noDataValue, dstLayer, idField, elevField, callback, callback_data); + + [Obsolete("Use CreatePansharpenedVRT(string pszXML, Band panchroBand, Band[] nInputSpectralBands) instead.")] + public static Dataset CreatePansharpenedVRT(string pszXML, Band panchroBand, int nInputSpectralBands, Band[] ahInputSpectralBands) + => CreatePansharpenedVRT(pszXML, panchroBand, ahInputSpectralBands); + + [Obsolete("Use BuildVRT(string dest, Dataset[] object_list_count, GDALBuildVRTOptions options, GDALProgressFuncDelegate callback, string callback_data) instead.", error: true)] + public static Dataset wrapper_GDALBuildVRT_objects(string dest, int object_list_count, IntPtr poObjects, GDALBuildVRTOptions options, GDALProgressFuncDelegate callback, string callback_data) + => throw new NotSupportedException(); + + [Obsolete("Use MultiDimTranslate(string dest, Dataset[] object_list_count, GDALMultiDimTranslateOptions multiDimTranslateOptions, GDALProgressFuncDelegate callback, string callback_data) instead.", error: true)] + public static Dataset wrapper_GDALMultiDimTranslateDestName(string dest, int object_list_count, IntPtr poObjects, GDALMultiDimTranslateOptions multiDimTranslateOptions, GDALProgressFuncDelegate callback, string callback_data) + => throw new NotSupportedException(); + + [Obsolete("Use Contour(Dataset dstDS, Dataset srcDS, GDALContourOptions options, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public static int wrapper_GDALContourDestDS(Dataset dstDS, Dataset srcDS, GDALContourOptions options, GDALProgressFuncDelegate callback, string callback_data) + => Contour(dstDS, srcDS, options, callback, callback_data); + + [Obsolete("Use Contour(string dest, Dataset srcDS, GDALContourOptions options, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public static Dataset wrapper_GDALContourDestName(string dest, Dataset srcDS, GDALContourOptions options, GDALProgressFuncDelegate callback, string callback_data) + => Contour(dest, srcDS, options, callback, callback_data); + + [Obsolete("Use DEMProcessing(string dest, Dataset dataset, string pszProcessing, string pszColorFilename, GDALDEMProcessingOptions options, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public static Dataset wrapper_GDALDEMProcessing(string dest, Dataset dataset, string pszProcessing, string pszColorFilename, GDALDEMProcessingOptions options, GDALProgressFuncDelegate callback, string callback_data) + => DEMProcessing(dest, dataset, pszProcessing, pszColorFilename, options, callback, callback_data); + + [Obsolete("Use Footprint(Dataset dstDS, Dataset srcDS, GDALFootprintOptions options, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public static int wrapper_GDALFootprintDestDS(Dataset dstDS, Dataset srcDS, GDALFootprintOptions options, GDALProgressFuncDelegate callback, string callback_data) + => Footprint(dstDS, srcDS, options, callback, callback_data); + + [Obsolete("Use Footprint(string dest, Dataset srcDS, GDALFootprintOptions options, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public static Dataset wrapper_GDALFootprintDestName(string dest, Dataset srcDS, GDALFootprintOptions options, GDALProgressFuncDelegate callback, string callback_data) + => Footprint(dest, srcDS, options, callback, callback_data); + + [Obsolete("Use Grid(string dest, Dataset dataset, GDALGridOptions options, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public static Dataset wrapper_GDALGrid(string dest, Dataset dataset, GDALGridOptions options, GDALProgressFuncDelegate callback, string callback_data) + => Grid(dest, dataset, options, callback, callback_data); + + [Obsolete("Use Nearblack(Dataset dstDS, Dataset srcDS, GDALNearblackOptions options, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public static int wrapper_GDALNearblackDestDS(Dataset dstDS, Dataset srcDS, GDALNearblackOptions options, GDALProgressFuncDelegate callback, string callback_data) + => Nearblack(dstDS, srcDS, options, callback, callback_data); + + [Obsolete("Use Nearblack(string dest, Dataset srcDS, GDALNearblackOptions options, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public static Dataset wrapper_GDALNearblackDestName(string dest, Dataset srcDS, GDALNearblackOptions options, GDALProgressFuncDelegate callback, string callback_data) + => Nearblack(dest, srcDS, options, callback, callback_data); + + [Obsolete("Use Rasterize(Dataset dstDS, Dataset srcDS, GDALRasterizeOptions options, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public static int wrapper_GDALRasterizeDestDS(Dataset dstDS, Dataset srcDS, GDALRasterizeOptions options, GDALProgressFuncDelegate callback, string callback_data) + => Rasterize(dstDS, srcDS, options, callback, callback_data); + + [Obsolete("Use Rasterize(string dest, Dataset srcDS, GDALRasterizeOptions options, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public static Dataset wrapper_GDALRasterizeDestName(string dest, Dataset srcDS, GDALRasterizeOptions options, GDALProgressFuncDelegate callback, string callback_data) + => Rasterize(dest, srcDS, options, callback, callback_data); + + [Obsolete("Use Translate(string dest, Dataset dataset, GDALTranslateOptions translateOptions, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public static Dataset wrapper_GDALTranslate(string dest, Dataset dataset, GDALTranslateOptions translateOptions, GDALProgressFuncDelegate callback, string callback_data) + => Translate(dest, dataset, translateOptions, callback, callback_data); + + [Obsolete("Use VectorTranslate(Dataset dstDS, Dataset srcDS, GDALVectorTranslateOptions options, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public static int wrapper_GDALVectorTranslateDestDS(Dataset dstDS, Dataset srcDS, GDALVectorTranslateOptions options, GDALProgressFuncDelegate callback, string callback_data) + => VectorTranslate(dstDS, srcDS, options, callback, callback_data); + + [Obsolete("Use VectorTranslate(string dest, Dataset srcDS, GDALVectorTranslateOptions options, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public static Dataset wrapper_GDALVectorTranslateDestName(string dest, Dataset srcDS, GDALVectorTranslateOptions options, GDALProgressFuncDelegate callback, string callback_data) + => VectorTranslate(dest, srcDS, options, callback, callback_data); + + [Obsolete("Use TileIndex(string dest, string[] source_filenames, GDALTileIndexOptions options, GDALProgressFuncDelegate callback, string callback_data) instead.")] + public static Dataset wrapper_TileIndex_names(string dest, string[] source_filenames, GDALTileIndexOptions options, GDALProgressFuncDelegate callback, string callback_data) + => TileIndex(dest, source_filenames, options, callback, callback_data); + + [Obsolete("Use the GCP.GCPX property instead.")] + public static double GDAL_GCP_GCPX_get(GCP gcp) => gcp.GCPX; + [Obsolete("Use the GCP.GCPX property instead.")] + public static void GDAL_GCP_GCPX_set(GCP gcp, double dfGCPX) => gcp.GCPX = dfGCPX; + [Obsolete("Use the GCP.GCPY property instead.")] + public static double GDAL_GCP_GCPY_get(GCP gcp) => gcp.GCPY; + [Obsolete("Use the GCP.GCPY property instead.")] + public static void GDAL_GCP_GCPY_set(GCP gcp, double dfGCPY) => gcp.GCPY = dfGCPY; + [Obsolete("Use the GCP.GCPZ property instead.")] + public static double GDAL_GCP_GCPZ_get(GCP gcp) => gcp.GCPZ; + [Obsolete("Use the GCP.GCPZ property instead.")] + public static void GDAL_GCP_GCPZ_set(GCP gcp, double dfGCPZ) => gcp.GCPZ = dfGCPZ; + [Obsolete("Use the GCP.GCPPixel property instead.")] + public static double GDAL_GCP_GCPPixel_get(GCP gcp) => gcp.GCPPixel; + [Obsolete("Use the GCP.GCPPixel property instead.")] + public static void GDAL_GCP_GCPPixel_set(GCP gcp, double dfGCPPixel) => gcp.GCPPixel = dfGCPPixel; + [Obsolete("Use the GCP.GCPLine property instead.")] + public static double GDAL_GCP_GCPLine_get(GCP gcp) => gcp.GCPLine; + [Obsolete("Use the GCP.GCPLine property instead.")] + public static void GDAL_GCP_GCPLine_set(GCP gcp, double dfGCPLine) => gcp.GCPLine = dfGCPLine; + [Obsolete("Use the GCP.Info property instead.")] + public static string GDAL_GCP_Info_get(GCP gcp) => gcp.Info; + [Obsolete("Use the GCP.Info property instead.")] + public static void GDAL_GCP_Info_set(GCP gcp, string pszInfo) => gcp.Info = pszInfo; + [Obsolete("Use the GCP.Id property instead.")] + public static string GDAL_GCP_Id_get(GCP gcp) => gcp.Id; + [Obsolete("Use the GCP.Id property instead.")] + public static void GDAL_GCP_Id_set(GCP gcp, string pszId) => gcp.Id = pszId; + [Obsolete("Use the GCP.GCPX property instead.")] + public static double GDAL_GCP_get_GCPX(GCP gcp) => gcp.GCPX; + [Obsolete("Use the GCP.GCPX property instead.")] + public static void GDAL_GCP_set_GCPX(GCP gcp, double dfGCPX) => gcp.GCPX = dfGCPX; + [Obsolete("Use the GCP.GCPY property instead.")] + public static double GDAL_GCP_get_GCPY(GCP gcp) => gcp.GCPY; + [Obsolete("Use the GCP.GCPY property instead.")] + public static void GDAL_GCP_set_GCPY(GCP gcp, double dfGCPY) => gcp.GCPY = dfGCPY; + [Obsolete("Use the GCP.GCPZ property instead.")] + public static double GDAL_GCP_get_GCPZ(GCP gcp) => gcp.GCPZ; + [Obsolete("Use the GCP.GCPZ property instead.")] + public static void GDAL_GCP_set_GCPZ(GCP gcp, double dfGCPZ) => gcp.GCPZ = dfGCPZ; + [Obsolete("Use the GCP.GCPPixel property instead.")] + public static double GDAL_GCP_get_GCPPixel(GCP gcp) => gcp.GCPPixel; + [Obsolete("Use the GCP.GCPPixel property instead.")] + public static void GDAL_GCP_set_GCPPixel(GCP gcp, double dfGCPPixel) => gcp.GCPPixel = dfGCPPixel; + [Obsolete("Use the GCP.GCPLine property instead.")] + public static double GDAL_GCP_get_GCPLine(GCP gcp) => gcp.GCPLine; + [Obsolete("Use the GCP.GCPLine property instead.")] + public static void GDAL_GCP_set_GCPLine(GCP gcp, double dfGCPLine) => gcp.GCPLine = dfGCPLine; + [Obsolete("Use the GCP.Info property instead.")] + public static string GDAL_GCP_get_Info(GCP gcp) => gcp.Info; + [Obsolete("Use the GCP.Info property instead.")] + public static void GDAL_GCP_set_Info(GCP gcp, string pszInfo) => gcp.Info = pszInfo; + [Obsolete("Use the GCP.Id property instead.")] + public static string GDAL_GCP_get_Id(GCP gcp) => gcp.Id; + [Obsolete("Use the GCP.Id property instead.")] + public static void GDAL_GCP_set_Id(GCP gcp, string pszId) => gcp.Id = pszId; +%} + +/* + * C# extension method class + */ +%{ +typedef struct {} GdalExtensions; +%} +%typemap(csclassmodifiers) GdalExtensions "public static class"; +%typemap(csinterfaces) GdalExtensions ""; +%typemap(csdisposing) GdalExtensions ""; +%typemap(csdispose) GdalExtensions ""; +%typemap(csbody) GdalExtensions %{ + public static Dataset GetDataset(this OGR.Layer layer) => Gdal.GetDatasetFromLayer(layer); +%} + +%ignore GdalExtensions::GdalExtensions(); +struct GdalExtensions{}; + +/***************************************************************************** + * Enable C# default arguments all GDAL methods * + * Apply fixes to specific methods to translate C++ default values to C# * + ****************************************************************************/ + +#if SWIG_VERSION >= 0x040200 +%feature("cs:defaultargs"); + +%feature("cs:defaultargs", eType="DataType.GDT_Byte", options="null") GDALDatasetShadow::Create; +%feature("cs:defaultargs", options="null") GDALDatasetShadow::CreateVector; +%feature("cs:defaultargs", root_group_options="null", options="null") GDALDatasetShadow::CreateMultiDimensional; +%feature("cs:defaultargs", options="null", callback="null", callback_data="null") GDALDatasetShadow::CreateCopy; + +%feature("cs:defaultargs", callback="null", callback_data="null") GDALAlgorithmHS::Run; +%feature("cs:defaultargs", callback="null", callback_data="null") GDALAlgorithmHS::ParseRunAndFinalize; + +%feature("cs:defaultargs", options="null") GDALGroupHS::GetMDArrayNames; +%feature("cs:defaultargs", options="null") GDALGroupHS::OpenMDArray; +%feature("cs:defaultargs", options="null") GDALGroupHS::OpenMDArrayFromFullname; +%feature("cs:defaultargs", options="null") GDALGroupHS::ResolveMDArray; +%feature("cs:defaultargs", options="null") GDALGroupHS::GetGroupNames; +%feature("cs:defaultargs", options="null") GDALGroupHS::OpenGroup; +%feature("cs:defaultargs", options="null") GDALGroupHS::OpenGroupFromFullname; +%feature("cs:defaultargs", options="null") GDALGroupHS::GetVectorLayerNames; +%feature("cs:defaultargs", options="null") GDALGroupHS::OpenVectorLayer; +%feature("cs:defaultargs", options="null") GDALGroupHS::CreateGroup; +%feature("cs:defaultargs", options="null") GDALGroupHS::DeleteGroup; +%feature("cs:defaultargs", options="null") GDALGroupHS::CreateDimension; +%feature("cs:defaultargs", options="null") GDALGroupHS::DeleteMDArray; +%feature("cs:defaultargs", options="null") GDALGroupHS::DeleteAttribute; +%feature("cs:defaultargs", options="null") GDALGroupHS::CreateAttribute; +%feature("cs:defaultargs", options="null") GDALGroupHS::SubsetDimensionFromSelection; +%feature("cs:defaultargs", groupOptions="null", arrayOptions="null") GDALGroupHS::GetMDArrayFullNamesRecursive; + +%feature("cs:defaultargs", extraArg="null") GDALRasterBandShadow::ReadRaster; +%feature("cs:defaultargs", extraArg="null") GDALRasterBandShadow::WriteRaster; +%feature("cs:defaultargs", callback="null", callback_data="null", options="null") GDALRasterBandShadow::ComputeStatistics; +%feature("cs:defaultargs", histogram="null", include_out_of_range="false", approx_ok="true", callback="null", callback_data="null") GDALRasterBandShadow::GetHistogram; +%feature("cs:defaultargs", histogram="null", include_out_of_range="false", approx_ok="true", callback="null", callback_data="null") GDALRasterBandShadow::GetHistogramEx; +%feature("cs:defaultargs", force="true", callback="null", callback_data="null") GDALRasterBandShadow::GetDefaultHistogram; +%feature("cs:defaultargs", force="true", callback="null", callback_data="null") GDALRasterBandShadow::GetDefaultHistogramEx; +%feature("cs:defaultargs", buf_type="DataType.GDT_Byte", options="null") GDALRasterBandShadow::AdviseRead; +%feature("cs:defaultargs", transformerOptions="null") GDALRasterBandShadow::InterpolateAtGeolocation; + +%feature("cs:defaultargs", buf_type="DataType.GDT_Byte", band_list="null", options="null") GDALDatasetShadow::AdviseRead; +%feature("cs:defaultargs", overviewlist="null") GDALDatasetShadow::BuildOverviews; +%feature("cs:defaultargs", srs="null") GDALDatasetShadow::GetExtent; +%feature("cs:defaultargs", srs="null", geom_type="wkbGeometryType.wkbUnknown", options="null") GDALDatasetShadow::CreateLayer; +%feature("cs:defaultargs", datatype="DataType.GDT_Byte") GDALDatasetShadow::AddBand; +%feature("cs:defaultargs", spatialFilter="null") GDALDatasetShadow::ExecuteSQL; +%feature("cs:defaultargs", force=0) GDALDatasetShadow::StartTransaction; +%feature("cs:defaultargs", extraArg="null") GDALDatasetShadow::ReadRaster; +%feature("cs:defaultargs", extraArg="null") GDALDatasetShadow::WriteRaster; +%feature("cs:defaultargs", callback="null", callback_data="null", options="null") GDALDatasetShadow::BuildOverviews; +%feature("cs:defaultargs", callback="null", callback_data="null") GDALDatasetShadow::GetNextFeature; +%feature("cs:defaultargs", callback="null", callback_data="null") GDALDatasetShadow::Close; +%feature("cs:defaultargs", options="null") GDALDatasetShadow::AddBand; +%feature("cs:defaultargs", options="null") GDALDatasetShadow::CreateLayerFromGeomFieldDefn; +%feature("cs:defaultargs", options="null") GDALDatasetShadow::CopyLayer; +%feature("cs:defaultargs", options="null") GDALDatasetShadow::GetFieldDomainNames; +%feature("cs:defaultargs", options="null") GDALDatasetShadow::GetRelationshipNames; +%feature("cs:defaultargs", options="null") GDALDatasetShadow::AsMDArray; +%feature("cs:defaultargs", hSRS="null") GDALDatasetShadow::SetGCPs2; + +%feature("cs:defaultargs", eType="DataType.GDT_Byte", options="null") GDALDriverShadow::Create; +%feature("cs:defaultargs", options="null") GDALDriverShadow::Create; +%feature("cs:defaultargs", options="null") GDALDriverShadow::CreateVector; +%feature("cs:defaultargs", root_group_options="null", options="null") GDALDriverShadow::CreateMultiDimensional; +%feature("cs:defaultargs", options="null", callback="null", callback_data="null") GDALDriverShadow::CreateCopy; + +%feature("cs:defaultargs", callback="null", callback_data="null", options="null") GDALTransformerInfoShadow::TransformGeolocations; + +%feature("cs:defaultargs", eSubType="ExtendedDataTypeSubType.GEDTST_NONE") GDALExtendedDataTypeHS::CreateString; + +%feature("cs:defaultargs", palette="PaletteInterp.GPI_RGB") GDALColorTableShadow::GDALColorTableShadow; + +%feature("cs:defaultargs", options="null") GDALMDArrayHS::Resize; +%feature("cs:defaultargs", options="null") GDALMDArrayHS::CreateAttribute; +%feature("cs:defaultargs", options="null") GDALMDArrayHS::DeleteAttribute; +%feature("cs:defaultargs", storageType="DataType.GDT_Unknown") GDALMDArrayHS::SetOffset; +%feature("cs:defaultargs", storageType="DataType.GDT_Unknown") GDALMDArrayHS::SetScale; +%feature("cs:defaultargs", options="null") GDALMDArrayHS::GetMask; +%feature("cs:defaultargs", xArray="null", yArray="null", options="null") GDALMDArrayHS::GetGridded; +%feature("cs:defaultargs", hRootGroup="null", options="null") GDALMDArrayHS::AsClassicDataset; +%feature("cs:defaultargs", options="null") GDALMDArrayHS::Cache; +%feature("cs:defaultargs", overviewlist="null", callback="null", callback_data="null", options="null") GDALMDArrayHS::BuildOverviews; + +%feature("cs:defaultargs", pfnTransformer="null", pTransformArg="default(IntPtr)", burn_values="null", options="null", callback="null", callback_data="null") RasterizeLayers; +%feature("cs:defaultargs", callback="null", callback_data="null") RegenerateOverviews; +%feature("cs:defaultargs", callback="null", callback_data="null") RegenerateOverview; +%feature("cs:defaultargs", pfnErrorHandler="null", user_data="default(IntPtr)") SetErrorHandler; +%feature("cs:defaultargs", pszCallbackName="null") PushErrorHandler; +%feature("cs:defaultargs", msg_class="CPLErr.CE_Failure") Error; +%feature("cs:defaultargs", scheme=3) EscapeString; //CPLES_SQL +%feature("cs:defaultargs", pszDefault="null") wrapper_CPLGetConfigOption; +%feature("cs:defaultargs", pszDefault="null") wrapper_CPLGetGlobalConfigOption; +%feature("cs:defaultargs", pszDefault="null") wrapper_CPLGetThreadLocalConfigOption; +%feature("cs:defaultargs", pszDefault="null") wrapper_VSIGetCredential; +%feature("cs:defaultargs", pszDefault="null") wrapper_VSIGetPathSpecificOption; +%feature("cs:defaultargs", pszPathPrefix="null") wrapper_VSIClearCredentials; +%feature("cs:defaultargs", pszPathPrefix="null") wrapper_VSIClearPathSpecificOptions; +%feature("cs:defaultargs", options="null", callback="null", callback_data="null") wrapper_VSIMove; +%feature("cs:defaultargs", fpSource="default(IntPtr)", options="null", callback="null", callback_data="null") wrapper_VSICopyFile; +%feature("cs:defaultargs", options="null") wrapper_VSIGetSignedURL; +%feature("cs:defaultargs", options="null") wrapper_VSIGetFileMetadata; +%feature("cs:defaultargs", options="null") wrapper_VSISetFileMetadata; +%feature("cs:defaultargs", options="null") wrapper_VSINetworkStatsGetAsSerializedJSON; +%feature("cs:defaultargs", bSetError=0, options="null") wrapper_VSIFOpenExL; +%feature("cs:defaultargs", callback="null", callback_data="null") ComputeMedianCutPCT; +%feature("cs:defaultargs", callback="null", callback_data="null") DitherRGB2PCT; +%feature("cs:defaultargs", src_wkt="null", dst_wkt="null", eResampleAlg="ResampleAlg.GRA_NearestNeighbour", callback="null", callback_data="null", options="null") ReprojectImage; +%feature("cs:defaultargs", callback="null", callback_data="null", options="null") Polygonize; +%feature("cs:defaultargs", callback="null", callback_data="null", options="null") FPolygonize; +%feature("cs:defaultargs", callback="null", callback_data="null", options="null") FillNodata; +%feature("cs:defaultargs", callback="null", callback_data="null", options="null") SieveFilter; +%feature("cs:defaultargs", callback="null", callback_data="null") RegenerateOverview; +%feature("cs:defaultargs", callback="null", callback_data="null") ContourGenerate; +%feature("cs:defaultargs", callback="null", callback_data="null", options="null") ContourGenerateEx; +%feature("cs:defaultargs", heightMode="ViewshedOutputType.GVOT_NORMAL", callback="null", callback_data="null", options="null") ViewshedGenerate; +%feature("cs:defaultargs", options="null") IsLineOfSightVisible; +%feature("cs:defaultargs", options="null") ApplyVerticalShiftGrid; +%feature("cs:defaultargs", src_wkt="null", dst_wkt="null", eResampleAlg="ResampleAlg.GRA_NearestNeighbour") AutoCreateWarpedVRT; +%feature("cs:defaultargs", options="null", callback="null", callback_data="null") ComputeProximity; +%feature("cs:defaultargs", options="null") GetJPEG2000StructureAsString; +%feature("cs:defaultargs", eAccess="Access.GA_ReadOnly") Open; +%feature("cs:defaultargs", eAccess="Access.GA_ReadOnly") OpenShared; +%feature("cs:defaultargs", allowed_drivers="null", open_options="null", sibling_files="null") OpenEx; +%feature("cs:defaultargs", papszSiblings="null") IdentifyDriver; +%feature("cs:defaultargs", allowed_drivers="null", sibling_files="null") IdentifyDriverEx; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALTranslate; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALWarpDestDS; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALWarpDestName; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALVectorTranslateDestDS; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALVectorTranslateDestName; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALDEMProcessing; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALNearblackDestDS; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALNearblackDestName; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALGrid; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALContourDestDS; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALContourDestName; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALRasterizeDestDS; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALRasterizeDestName; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALFootprintDestDS; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALFootprintDestName; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALBuildVRT_objects; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALBuildVRT_names; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_TileIndex_names; +%feature("cs:defaultargs", callback="null", callback_data="null") wrapper_GDALMultiDimTranslateDestName; + +#endif //SWIG_VERSION >= 0x040200 diff --git a/swig/include/csharp/gdal_csharp_extend.i b/swig/include/csharp/gdal_csharp_extend.i index 3a615c158bd2..ec1966d8f2b0 100644 --- a/swig/include/csharp/gdal_csharp_extend.i +++ b/swig/include/csharp/gdal_csharp_extend.i @@ -19,27 +19,15 @@ %extend GDALRasterBandShadow { %apply (void *buffer_ptr) {void *buffer}; - CPLErr ReadRaster(int xOff, int yOff, int xSize, int ySize, void* buffer, - int buf_xSize, int buf_ySize, GDALDataType buf_type, - int pixelSpace, int lineSpace) { - return GDALRasterIO( self, GF_Read, xOff, yOff, xSize, ySize, - buffer, buf_xSize, buf_ySize, buf_type, pixelSpace, lineSpace ); - } - CPLErr WriteRaster(int xOff, int yOff, int xSize, int ySize, void* buffer, - int buf_xSize, int buf_ySize, GDALDataType buf_type, - int pixelSpace, int lineSpace) { - return GDALRasterIO( self, GF_Write, xOff, yOff, xSize, ySize, - buffer, buf_xSize, buf_ySize, buf_type, pixelSpace, lineSpace ); - } CPLErr ReadRaster(int xOff, int yOff, int xSize, int ySize, void* buffer, int buf_xSize, int buf_ySize, GDALDataType buf_type, - int pixelSpace, int lineSpace, GDALRasterIOExtraArg* extraArg) { + GIntBig pixelSpace, GIntBig lineSpace, GDALRasterIOExtraArg* extraArg = NULL) { return GDALRasterIOEx( self, GF_Read, xOff, yOff, xSize, ySize, buffer, buf_xSize, buf_ySize, buf_type, pixelSpace, lineSpace, extraArg ); } CPLErr WriteRaster(int xOff, int yOff, int xSize, int ySize, void* buffer, int buf_xSize, int buf_ySize, GDALDataType buf_type, - int pixelSpace, int lineSpace, GDALRasterIOExtraArg* extraArg) { + GIntBig pixelSpace, GIntBig lineSpace, GDALRasterIOExtraArg* extraArg = NULL) { return GDALRasterIOEx( self, GF_Write, xOff, yOff, xSize, ySize, buffer, buf_xSize, buf_ySize, buf_type, pixelSpace, lineSpace, extraArg ); } @@ -49,53 +37,30 @@ %extend GDALDatasetShadow { %apply (void *buffer_ptr) {void *buffer}; - %apply (int argin[ANY]) {int *bandMap}; - CPLErr ReadRaster(int xOff, int yOff, int xSize, int ySize, void* buffer, - int buf_xSize, int buf_ySize, GDALDataType buf_type, - int bandCount, int* bandMap, int pixelSpace, int lineSpace, int bandSpace) { - return GDALDatasetRasterIO( self, GF_Read, xOff, yOff, xSize, ySize, - buffer, buf_xSize, buf_ySize, buf_type, bandCount, - bandMap, pixelSpace, lineSpace, bandSpace); - } - CPLErr WriteRaster(int xOff, int yOff, int xSize, int ySize, void* buffer, - int buf_xSize, int buf_ySize, GDALDataType buf_type, - int bandCount, int* bandMap, int pixelSpace, int lineSpace, int bandSpace) { - return GDALDatasetRasterIO( self, GF_Write, xOff, yOff, xSize, ySize, - buffer, buf_xSize, buf_ySize, buf_type, bandCount, - bandMap, pixelSpace, lineSpace, bandSpace); - } + %apply (int INPUT[]) {int *bandMap}; CPLErr ReadRaster(int xOff, int yOff, int xSize, int ySize, void* buffer, int buf_xSize, int buf_ySize, GDALDataType buf_type, - int bandCount, int* bandMap, int pixelSpace, int lineSpace, int bandSpace, - GDALRasterIOExtraArg* extraArg) { + int bandCount, int* bandMap, GIntBig pixelSpace, GIntBig lineSpace, GIntBig bandSpace, + GDALRasterIOExtraArg* extraArg = NULL) { return GDALDatasetRasterIOEx( self, GF_Read, xOff, yOff, xSize, ySize, buffer, buf_xSize, buf_ySize, buf_type, bandCount, bandMap, pixelSpace, lineSpace, bandSpace, extraArg); } CPLErr WriteRaster(int xOff, int yOff, int xSize, int ySize, void* buffer, int buf_xSize, int buf_ySize, GDALDataType buf_type, - int bandCount, int* bandMap, int pixelSpace, int lineSpace, int bandSpace, - GDALRasterIOExtraArg* extraArg) { + int bandCount, int* bandMap, GIntBig pixelSpace, GIntBig lineSpace, GIntBig bandSpace, + GDALRasterIOExtraArg* extraArg = NULL) { return GDALDatasetRasterIOEx( self, GF_Write, xOff, yOff, xSize, ySize, buffer, buf_xSize, buf_ySize, buf_type, bandCount, bandMap, pixelSpace, lineSpace, bandSpace, extraArg); } %clear void *buffer; %clear int* bandMap; - - %apply (void *buffer_ptr) {const GDAL_GCP* __GetGCPs}; - const GDAL_GCP* __GetGCPs( ) { - return GDALGetGCPs( self ); - } - %clear const GDAL_GCP* __GetGCPs; - - CPLErr __SetGCPs( int nGCPs, GDAL_GCP const *pGCPs, const char *pszGCPProjection ) { - return GDALSetGCPs( self, nGCPs, pGCPs, pszGCPProjection ); - } - IMPLEMENT_ARRAY_MARSHALER(GDAL_GCP) } -IMPLEMENT_ARRAY_MARSHALER_STATIC(GDAL_GCP) - - - +%inline +{ + static GDALDatasetShadow* GetDatasetFromLayer(OGRLayerShadow *layer) { + return OGR_L_GetDataset(layer); + } +} diff --git a/swig/include/csharp/ogr_csharp.i b/swig/include/csharp/ogr_csharp.i index 44471baa167f..19d7de1c1cbb 100644 --- a/swig/include/csharp/ogr_csharp.i +++ b/swig/include/csharp/ogr_csharp.i @@ -28,51 +28,206 @@ DEFINE_EXTERNAL_CLASS(GDALMajorObjectShadow, OSGeo.GDAL.MajorObject) %typemap(cscode, noblock="1") OGRGeometryShadow { - public int ExportToWkb( byte[] buffer, wkbByteOrder byte_order ) { - int retval; - long size = WkbSize(); - if (size > Int32.MaxValue) - throw new ArgumentException("Too big geometry (ExportToWkb)"); - if (buffer.Length < size) - throw new ArgumentException("Buffer size is small (ExportToWkb)"); - - IntPtr ptr = Marshal.AllocHGlobal((int)size * Marshal.SizeOf(buffer[0])); - try { - retval = ExportToWkb((int)size, ptr, byte_order); - Marshal.Copy(ptr, buffer, 0, (int)size); - } finally { - Marshal.FreeHGlobal(ptr); - } - GC.KeepAlive(this); - return retval; + public byte[] ExportToWkb(wkbByteOrder byte_order = wkbByteOrder.wkbNDR) { + if (WkbLongSize > int.MaxValue) + throw new InvalidOperationException("The geometry is too larget to fit in a .NET array."); + var buffer = new byte[WkbLongSize]; + if (ExportToWkb(buffer, byte_order) != 0) + throw new ApplicationException("ExportToWkb return code did not indicate success."); + return buffer; } - public int ExportToWkb( byte[] buffer ) { - return ExportToWkb( buffer, wkbByteOrder.wkbXDR); + public int ExportToWkb(byte[] buffer, wkbByteOrder byte_order = wkbByteOrder.wkbNDR) { + var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); + try { + return ExportToWkb(new IntPtr(buffer.Length), handle.AddrOfPinnedObject(), byte_order); + } finally { + handle.Free(); + } + } + public byte[] ExportToIsoWkb(wkbByteOrder byte_order = wkbByteOrder.wkbNDR) { + if (WkbLongSize > int.MaxValue) + throw new InvalidOperationException("The geometry is too larget to fit in a .NET array."); + var buffer = new byte[WkbLongSize]; + if (ExportToIsoWkb(buffer, byte_order) != 0) + throw new ApplicationException("ExportToIsoWkb return code did not indicate success."); + return buffer; + } + public int ExportToIsoWkb(byte[] buffer, wkbByteOrder byte_order = wkbByteOrder.wkbNDR) { + var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); + try { + return ExportToIsoWkb(new IntPtr(buffer.Length), handle.AddrOfPinnedObject(), byte_order); + } finally { + handle.Free(); + } } public static $csclassname CreateFromWkb(byte[] wkb){ - if (wkb.Length == 0) - throw new ArgumentException("Buffer size is small (CreateFromWkb)"); - $csclassname retval; - IntPtr ptr = Marshal.AllocHGlobal(wkb.Length * Marshal.SizeOf(wkb[0])); - try { - Marshal.Copy(wkb, 0, ptr, wkb.Length); - retval = new $csclassname(wkbGeometryType.wkbUnknown, null, wkb.Length, ptr, null); - } finally { - Marshal.FreeHGlobal(ptr); - } - return retval; + return wkb.Length > 0 ? new Geometry(wkbGeometryType.wkbUnknown, null, wkb, null) + : throw new ArgumentException("Buffer size is small (CreateFromWkb)"); } public static $csclassname CreateFromWkt(string wkt){ - return new $csclassname(wkbGeometryType.wkbUnknown, wkt, 0, IntPtr.Zero, null); + return new $csclassname(wkbGeometryType.wkbUnknown, wkt, null, null); } public static $csclassname CreateFromGML(string gml){ - return new $csclassname(wkbGeometryType.wkbUnknown, null, 0, IntPtr.Zero, gml); + return new $csclassname(wkbGeometryType.wkbUnknown, null, null, gml); + } + +/* + * Overload to maintain backwards compatibility with multi-argument typemaps + */ + + [Obsolete("Use ExportToWkb(IntPtr length, IntPtr buffer_ptr, wkbByteOrder byte_order) instead.")] + public int ExportToWkb(int bufLen, IntPtr buffer, wkbByteOrder byte_order) + => ExportToWkb(new IntPtr(bufLen), buffer, byte_order); + + [Obsolete("Use $csclassname(wkbGeometryType type, string wkt, byte[] wkb, string gml) instead.")] + public $csclassname(wkbGeometryType type, string wkt, int wkb, IntPtr wkb_buf, string gml) + : this(type, wkt, PtrToByteArray(wkb, wkb_buf), gml) { } + + private static byte[] PtrToByteArray(int size, IntPtr ptr) { + if (size <= 0 || ptr == IntPtr.Zero) return null; + byte[] ret = new byte[size]; + Marshal.Copy(ptr, ret, 0, size); + return ret; + } +} + +%typemap(cscode, noblock="1") OGRFeatureShadow { + + public DateTime GetFieldAsDateTime(int id) { + GetFieldAsDateTime(id, out int year, out int month, out int day, out int hour, out int minute, out float second, out int tz); + return DateTimeFromParts(year, month, day, hour, minute, second, tz); + } + public DateTime GetFieldAsDateTime(string field_name) { + GetFieldAsDateTime(field_name, out int year, out int month, out int day, out int hour, out int minute, out float second, out int tz); + return DateTimeFromParts(year, month, day, hour, minute, second, tz); + } + public void SetField(int id, DateTime dateTime) { + DateTimeToParts(dateTime, out int year, out int month, out int day, out int hour, out int minute, out float second, out int tz); + SetField(id, year, month, day, hour, minute, second, tz); + } + public void SetField(string field_name, DateTime dateTime) { + DateTimeToParts(dateTime, out int year, out int month, out int day, out int hour, out int minute, out float second, out int tz); + SetField(field_name, year, month, day, hour, minute, second, tz); } - public Geometry(wkbGeometryType type) : this(OgrPINVOKE.new_Geometry((int)type, null, 0, IntPtr.Zero, null), true, null) { - if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve(); + private static DateTime DateTimeFromParts(int year, int month, int day, int hour, int minute, float second, int tz) { + var sec = (int)second; + var ms = (int)Math.Round((second - sec) * 1000); + DateTimeKind kind = tz == 100 ? DateTimeKind.Utc : tz == 1 ? DateTimeKind.Local : DateTimeKind.Unspecified; + return new DateTime(year, month, day, hour, minute, sec, ms, kind); + } + private static void DateTimeToParts(DateTime dateTime, out int year, out int month, out int day, out int hour, out int minute, out float second, out int tz) { + year = dateTime.Year; + month = dateTime.Month; + day = dateTime.Day; + hour = dateTime.Hour; + minute = dateTime.Minute; + second = dateTime.Second + dateTime.Millisecond / 1000f; + tz = dateTime.Kind == DateTimeKind.Utc ? 100 : dateTime.Kind == DateTimeKind.Local ? 1 : 0; } + +/* + * Overloads to maintain backwards compatibility with multi-argument typemaps + */ + [Obsolete("Use SetFieldDoubleList(int id, double[] nList) instead.")] + public void SetFieldDoubleList(int id, int nList, double[] pList) + => SetFieldDoubleList(id, pList); + [Obsolete("Use SetFieldIntegerList(int id, int[] nList) instead.")] + public void SetFieldIntegerList(int id, int nList, int[] pList) + => SetFieldIntegerList(id, pList); + [Obsolete("Use SetFromWithMap(Feature other, int forgiving, int[] nList) instead.")] + public int SetFromWithMap(Feature other, int forgiving, int nList, int[] pList) + => SetFromWithMap(other, forgiving, pList); +} + +%typemap(cscode, noblock="1") OGRLayerShadow { + [Obsolete("Use ReorderFields(int[] nList) instead.")] + public int ReorderFields(int nList, int[] pList) + => ReorderFields(pList); + [Obsolete("Use UpdateFeature(Feature feature, int[] nUpdatedFieldsCount, int[] nUpdatedGeomFieldsCount, bool bUpdateStyleString) instead.")] + public int UpdateFeature(Feature feature, int nUpdatedFieldsCount, int[] panUpdatedFieldsIdx, int nUpdatedGeomFieldsCount, int[] panUpdatedGeomFieldsIdx, bool bUpdateStyleString) + => UpdateFeature(feature, panUpdatedFieldsIdx, panUpdatedGeomFieldsIdx, bUpdateStyleString); } + +%pragma(csharp) modulecode=%{ + public static Geometry CreateGeometryFromEnvelope(Envelope envelope, OSR.SpatialReference reference = null) + => CreateGeometryFromEnvelope(envelope.MinX, envelope.MinY, envelope.MaxX, envelope.MaxY, reference); + + public static Geometry CreateGeometryFromWkb(byte[] buffer, OSR.SpatialReference reference = null) { + var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); + try { + return CreateGeometryFromWkb(new IntPtr(buffer.Length), handle.AddrOfPinnedObject(), reference); + } finally { + handle.Free(); + } + } + + [Obsolete("Use CreateGeometryFromWkb(IntPtr len, IntPtr bin_string, SpatialReference reference) instead.")] + public static Geometry CreateGeometryFromWkb(uint len, IntPtr bin_string, OSR.SpatialReference reference) + => CreateGeometryFromWkb(new IntPtr(len), bin_string, reference); +%} + +/***************************************************************************** + * Enable C# default arguments all OGR methods * + * Apply fixes to specific methods to translate C++ default values to C# * + ****************************************************************************/ + +#if SWIG_VERSION >= 0x040200 && !defined(FROM_GDAL_I) +%feature("cs:defaultargs"); + +%feature("cs:defaultargs", options="null", callback="null", callback_data="null") OGRLayerShadow::Intersection; +%feature("cs:defaultargs", options="null", callback="null", callback_data="null") OGRLayerShadow::Union; +%feature("cs:defaultargs", options="null", callback="null", callback_data="null") OGRLayerShadow::SymDifference; +%feature("cs:defaultargs", options="null", callback="null", callback_data="null") OGRLayerShadow::Identity; +%feature("cs:defaultargs", options="null", callback="null", callback_data="null") OGRLayerShadow::Update; +%feature("cs:defaultargs", options="null", callback="null", callback_data="null") OGRLayerShadow::Clip; +%feature("cs:defaultargs", options="null", callback="null", callback_data="null") OGRLayerShadow::Erase; +%feature("cs:defaultargs", force="true") OGRLayerShadow::GetExtent(int, OGREnvelope*, bool); +%feature("cs:defaultargs", force="true") OGRLayerShadow::GetExtent3D; + +%feature("cs:defaultargs", options="null") OGRFeatureShadow::GetFieldAsISO8601DateTime; +%feature("cs:defaultargs", options="null") OGRFeatureShadow::GetFieldAsISO8601DateTime; +%feature("cs:defaultargs", options="null") OGRFeatureShadow::DumpReadableAsString; +%feature("cs:defaultargs", flags=0x7FFFFFEF, bEmitError=1) OGRFeatureShadow::Validate; //0x7FFFFFEF = OGR_F_VAL_ALL +%feature("cs:defaultargs", bNotNullableOnly=0, options="null") OGRFeatureShadow::FillUnsetWithDefault; + +%feature("cs:defaultargs", type="wkbGeometryType.wkbUnknown", wkt="null", wkb="null", gml="null") OGRGeometryShadow::OGRGeometryShadow; +%feature("cs:defaultargs", byte_order="wkbByteOrder.wkbNDR") OGRGeometryShadow::ExportToWkb; +%feature("cs:defaultargs", byte_order="wkbByteOrder.wkbNDR") OGRGeometryShadow::ExportToIsoWkb; +%feature("cs:defaultargs", altitude_mode="null") OGRGeometryShadow::ExportToKML; +%feature("cs:defaultargs", options="null") OGRGeometryShadow::ExportToJson; +%feature("cs:defaultargs", options="null") OGRGeometryShadow::MakeValid; +%feature("cs:defaultargs", options="null") OGRGeometryShadow::GetLinearGeometry; +%feature("cs:defaultargs", options="null") OGRGeometryShadow::GetCurveGeometry; +%feature("cs:defaultargs", argout="null") OGRGeometryShadow::GetPoint; +%feature("cs:defaultargs", argout="null") OGRGeometryShadow::GetPointZM; +%feature("cs:defaultargs", argout="null") OGRGeometryShadow::GetPoint_2D; +%feature("cs:defaultargs", bOnlyEdges=0) OGRGeometryShadow::DelaunayTriangulation; +%feature("cs:defaultargs", bLookForCircular=0) OGRGeometryShadow::HasCurveGeometry; + +%feature("cs:defaultargs", field_type="FieldType.OFTString") OGRFieldDefnShadow::OGRFieldDefnShadow; + +%feature("cs:defaultargs", srs="null", geom_type="wkbGeometryType.wkbUnknown", options="null") OGRDataSourceShadow::CreateLayer; +%feature("cs:defaultargs", options="null") OGRDataSourceShadow::CopyLayer; +%feature("cs:defaultargs", spatialFilter="null") OGRDataSourceShadow::ExecuteSQL; +%feature("cs:defaultargs", force=0) OGRDataSourceShadow::StartTransaction; + +%feature("cs:defaultargs", options="null") OGRDriverShadow::CreateDataSource; +%feature("cs:defaultargs", options="null") OGRDriverShadow::CopyDataSource; + +%feature("cs:defaultargs", field_type="wkbGeometryType.wkbUnknown") OGRGeomFieldDefnShadow::OGRGeomFieldDefnShadow; + +%feature("cs:defaultargs", name_null_ok="null") OGRFeatureDefnShadow::OGRFeatureDefnShadow; + +%feature("cs:defaultargs", options="null") OGRGeomTransformerShadow::OGRGeomTransformerShadow; + +%feature("cs:defaultargs", reference="null") CreateGeometryFromWkb; +%feature("cs:defaultargs", reference="null") CreateGeometryFromWkt; +%feature("cs:defaultargs", reference="null") CreateGeometryFromEnvelope; +%feature("cs:defaultargs", options="null") ForceTo; +%feature("cs:defaultargs", bSetM=0) GT_SetModifier; + +#endif //SWIG_VERSION >= 0x040200 && !defined(FROM_GDAL_I) diff --git a/swig/include/csharp/ogr_csharp_extend.i b/swig/include/csharp/ogr_csharp_extend.i index bd832143fe9b..14da88edcf95 100644 --- a/swig/include/csharp/ogr_csharp_extend.i +++ b/swig/include/csharp/ogr_csharp_extend.i @@ -18,11 +18,33 @@ %extend OGRGeometryShadow { - %apply (void *buffer_ptr) {char *buffer}; - OGRErr ExportToWkb( int bufLen, char *buffer, OGRwkbByteOrder byte_order ) { - if (bufLen < OGR_G_WkbSize( self )) +%immutable; + long long WkbLongSize; + OGRwkbGeometryType GeometryType; + +%apply (size_t native_size) {(size_t length)}; + OGRErr ExportToWkb( size_t length, void *buffer_ptr, OGRwkbByteOrder byte_order = wkbNDR ) { + if (length < OGR_G_WkbSizeEx( self )) { CPLError(CE_Failure, 1, "Array size is small (ExportToWkb)."); - return OGR_G_ExportToWkb(self, byte_order, (unsigned char*) buffer ); + return CE_Failure; + } + return OGR_G_ExportToWkb(self, byte_order, (unsigned char*) buffer_ptr ); + } + OGRErr ExportToIsoWkb( size_t length, void *buffer_ptr, OGRwkbByteOrder byte_order = wkbNDR ) { + if (length < OGR_G_WkbSizeEx( self )) { + CPLError(CE_Failure, 1, "Array size is small (ExportToIsoWkb)."); + return CE_Failure; + } + return OGR_G_ExportToIsoWkb(self, byte_order, (unsigned char*) buffer_ptr ); } - %clear char *buffer; +%clear (size_t length); } + +%{ + long long OGRGeometryShadow_WkbLongSize_get(OGRGeometryShadow *self) { + return static_cast(OGR_G_WkbSizeEx(self)); + } + OGRwkbGeometryType OGRGeometryShadow_GeometryType_get(OGRGeometryShadow *self) { + return OGR_G_GetGeometryType(self); + } +%} diff --git a/swig/include/csharp/osr_csharp.i b/swig/include/csharp/osr_csharp.i index ec928fdd8da3..ea1012e98859 100644 --- a/swig/include/csharp/osr_csharp.i +++ b/swig/include/csharp/osr_csharp.i @@ -53,3 +53,62 @@ OSRCRSInfoList* GetCRSInfoListFromDatabase( char* authName, int* pnListCount ) } %} +/* + * Overloads to maintain backwards compatibility with multi-argument typemaps + */ + +%typemap(cscode, noblock="1") OSRSpatialReferenceShadow { + [Obsolete("Use ExportToPCI(out string proj, out string units, out double[] params_) instead.")] + public int ExportToPCI(out string proj, out string units) + => ExportToPCI(out proj, out units, out _); + [Obsolete("Use ExportToUSGS(out int code, out int zone, out double[] params_, out int datum) instead.")] + public int ExportToUSGS(out int code, out int zone, out int datum) + => ExportToUSGS(out code, out zone, out _, out datum); + [Obsolete("Use SetDataAxisToSRSAxisMapping(int[] nList) instead.")] + public int SetDataAxisToSRSAxisMapping(int nList, int[] pList) + => SetDataAxisToSRSAxisMapping(pList); + [Obsolete("Use FindMatches(string[] options, out int[] confidence_values) instead.")] + public SpatialReference[] FindMatches(string[] options, out int nvalues, out int[] confidence_values) { + var ret = FindMatches(options, out confidence_values); + nvalues = confidence_values.Length; + return ret; + } +} +/* + * Overloads to maintain backwards compatibility with multi-argument typemaps + */ + +%typemap(cscode, noblock="1") OSRCoordinateTransformationShadow { + [Obsolete("Use TransformPoints(double[] x, double[] y, double[] z, double[] t, int[] success) instead.")] + public void TransformPoints(int nCount, double[] x, double[] y, double[] z) + => TransformPoints(x, y, z); +} + +/***************************************************************************** + * Enable C# default arguments all OSR methods * + * Apply fixes to specific methods to translate C++ default values to C# * + ****************************************************************************/ + +#if SWIG_VERSION >= 0x040200 && !defined(FROM_GDAL_I) +%feature("cs:defaultargs"); + +%feature("cs:defaultargs", options="null") OSRSpatialReferenceShadow::IsSame; +%feature("cs:defaultargs", options="null") OSRSpatialReferenceShadow::ExportToWkt; +%feature("cs:defaultargs", options="null") OSRSpatialReferenceShadow::ExportToCF1; +%feature("cs:defaultargs", options="null") OSRSpatialReferenceShadow::ExportToCF1Units; +%feature("cs:defaultargs", options="null") OSRSpatialReferenceShadow::ExportToPROJJSON; +%feature("cs:defaultargs", options="null") OSRSpatialReferenceShadow::ConvertToOtherProjection; +%feature("cs:defaultargs", target_key="null") OSRSpatialReferenceShadow::GetAuthorityName; +%feature("cs:defaultargs", target_key="null") OSRSpatialReferenceShadow::GetAuthorityCode; +%feature("cs:defaultargs", name="null") OSRSpatialReferenceShadow::PromoteTo3D; +%feature("cs:defaultargs", name="null") OSRSpatialReferenceShadow::DemoteTo2D; +%feature("cs:defaultargs", units="null") OSRSpatialReferenceShadow::ImportFromCF1; +%feature("cs:defaultargs", argin="null") OSRSpatialReferenceShadow::ImportFromPCI; +%feature("cs:defaultargs", argin="null") OSRSpatialReferenceShadow::ImportFromUSGS; + +%feature("cs:defaultargs", z="null", t="null", success="null") OSRCoordinateTransformationShadow::TransformPoints; +%feature("cs:defaultargs", z="null", t="null", errorCodes="null") OSRCoordinateTransformationShadow::TransformPointsWithErrorCodes; + +%feature("cs:defaultargs", options="null") CreateCoordinateTransformation; + +#endif //SWIG_VERSION >= 0x040200 && !defined(FROM_GDAL_I) diff --git a/swig/include/csharp/swig_csharp_extensions.i b/swig/include/csharp/swig_csharp_extensions.i index 67f4e57576fa..e0d4a4752f14 100644 --- a/swig/include/csharp/swig_csharp_extensions.i +++ b/swig/include/csharp/swig_csharp_extensions.i @@ -48,7 +48,9 @@ } // Proxy classes (base classes, i.e, not derived classes) %typemap(csbody) SWIGTYPE %{ - private HandleRef swigCPtr; + private HandleRef? $csclassname_swigCPtr; + private HandleRef swigCPtr { get { lock (m_LockObject) { return $csclassname_swigCPtr ?? throw new ObjectDisposedException(GetType().FullName); } } } + protected readonly object m_LockObject = new object(); protected bool swigCMemOwn; protected object swigParentRef; @@ -58,7 +60,7 @@ public $csclassname(IntPtr cPtr, bool cMemoryOwn, object parent) { swigCMemOwn = cMemoryOwn; swigParentRef = parent; - swigCPtr = new HandleRef(this, cPtr); + $csclassname_swigCPtr = new HandleRef(this, cPtr); } public static HandleRef getCPtr($csclassname obj) { @@ -90,13 +92,13 @@ %} -#if SWIG_VERSION > 0x020000 // Derived proxy classes %typemap(csbody_derived) SWIGTYPE %{ - private HandleRef swigCPtr; + private HandleRef? $csclassname_swigCPtr; + private HandleRef swigCPtr { get { lock (m_LockObject) { return $csclassname_swigCPtr ?? throw new ObjectDisposedException(GetType().FullName); } } } public $csclassname(IntPtr cPtr, bool cMemoryOwn, object parent) : base($modulePINVOKE.$csclassname_SWIGUpcast(cPtr), cMemoryOwn, parent) { - swigCPtr = new HandleRef(this, cPtr); + $csclassname_swigCPtr = new HandleRef(this, cPtr); } public static HandleRef getCPtr($csclassname obj) { @@ -126,62 +128,17 @@ } } %} -#else -// Derived proxy classes -%typemap(csbody_derived) SWIGTYPE %{ - private HandleRef swigCPtr; - public $csclassname(IntPtr cPtr, bool cMemoryOwn, object parent) : base($modulePINVOKE.$csclassnameUpcast(cPtr), cMemoryOwn, parent) { - swigCPtr = new HandleRef(this, cPtr); - } - public static HandleRef getCPtr($csclassname obj) { - return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; - } - public static HandleRef getCPtrAndDisown($csclassname obj, object parent) { - if (obj != null) - { - obj.swigCMemOwn = false; - obj.swigParentRef = parent; - return obj.swigCPtr; - } - else - { - return new HandleRef(null, IntPtr.Zero); - } - } - public static HandleRef getCPtrAndSetReference($csclassname obj, object parent) { - if (obj != null) - { - obj.swigParentRef = parent; - return obj.swigCPtr; - } - else - { - return new HandleRef(null, IntPtr.Zero); - } - } -%} -#endif - -// Typewrapper classes -%typemap(csbody) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{ - private HandleRef swigCPtr; - - public $csclassname(IntPtr cPtr, bool futureUse, object parent) { - swigCPtr = new HandleRef(this, cPtr); - } - - protected $csclassname() { - swigCPtr = new HandleRef(null, IntPtr.Zero); - } - - public static HandleRef getCPtr($csclassname obj) { - return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; +%typemap(csdispose) SWIGTYPE %{ + ~$csclassname() { + //Base class finalizer + Dispose(); } %} -%typemap(csdispose) SWIGTYPE %{ +%typemap(csdispose_derived) SWIGTYPE %{ ~$csclassname() { + //Derrived class finalizer Dispose(); } %} @@ -191,24 +148,24 @@ %} %typemap(csdisposing, methodname="Dispose", methodmodifiers="public") SWIGTYPE { - lock(this) { - if(swigCPtr.Handle != IntPtr.Zero && swigCMemOwn) { + lock(m_LockObject) { + if($csclassname_swigCPtr.HasValue && $csclassname_swigCPtr.Value.Handle != IntPtr.Zero && swigCMemOwn) { swigCMemOwn = false; $imcall; } - swigCPtr = new HandleRef(null, IntPtr.Zero); + $csclassname_swigCPtr = null; swigParentRef = null; GC.SuppressFinalize(this); } } -%typemap(csdisposing_derived, methodname="Dispose", methodmodifiers="public") TYPE { - lock(this) { - if(swigCPtr.Handle != IntPtr.Zero && swigCMemOwn) { +%typemap(csdisposing_derived, methodname="Dispose", methodmodifiers="public") SWIGTYPE { + lock(m_LockObject) { + if($csclassname_swigCPtr.HasValue && $csclassname_swigCPtr.Value.Handle != IntPtr.Zero && swigCMemOwn) { swigCMemOwn = false; $imcall; } - swigCPtr = new HandleRef(null, IntPtr.Zero); + $csclassname_swigCPtr = null; swigParentRef = null; GC.SuppressFinalize(this); base.Dispose(); @@ -229,68 +186,6 @@ protected static object ThisOwn_false() { return the$moduleObject; } %} - -/****************************************************************************** - * Generic functions to marshal SWIGTYPE arrays * - *****************************************************************************/ - -%define IMPLEMENT_ARRAY_MARSHALER(CTYPE) -%csmethodmodifiers __WriteCArrayItem_##CTYPE "private"; -%csmethodmodifiers __ReadCArrayItem_##CTYPE "private"; -%csmethodmodifiers __AllocCArray_##CTYPE "private"; -%csmethodmodifiers __FreeCArray_##CTYPE "private"; - %apply (void *buffer_ptr) {CTYPE* carray}; - %apply (void *buffer_ptr) {CTYPE* __AllocCArray_##CTYPE}; - void __WriteCArrayItem_##CTYPE(CTYPE* carray, int index, CTYPE* value) { - carray[index] = *value; - } - CTYPE* __ReadCArrayItem_##CTYPE(CTYPE* carray, int index) { - return &carray[index]; - } - CTYPE* __AllocCArray_##CTYPE(int size) { - return (CTYPE*)CPLMalloc(size * sizeof(CTYPE)); - } - void __FreeCArray_##CTYPE(CTYPE* carray) { - if (carray) - CPLFree(carray); - } - %clear CTYPE* carray; - %clear CTYPE* __AllocCArray_##CTYPE; -%enddef - -%define IMPLEMENT_ARRAY_MARSHALER_STATIC(CTYPE) -%csmethodmodifiers __WriteCArrayItem_##CTYPE "internal"; -%csmethodmodifiers __ReadCArrayItem_##CTYPE "internal"; -%csmethodmodifiers __AllocCArray_##CTYPE "internal"; -%csmethodmodifiers __FreeCArray_##CTYPE "internal"; - %apply (void *buffer_ptr) {CTYPE* carray}; - %apply (void *buffer_ptr) {CTYPE* __AllocCArray_##CTYPE}; -%inline %{ - void __WriteCArrayItem_##CTYPE(CTYPE* carray, int index, CTYPE* value) { - carray[index] = *value; - } -%} -%inline %{ - CTYPE* __ReadCArrayItem_##CTYPE(CTYPE* carray, int index) { - return &carray[index]; - } -%} -%inline %{ - CTYPE* __AllocCArray_##CTYPE(int size) { - return (CTYPE*)CPLMalloc(size * sizeof(CTYPE)); - } -%} -%inline %{ - void __FreeCArray_##CTYPE(CTYPE* carray) { - if (carray) - CPLFree(carray); - } -%} - %clear CTYPE* carray; - %clear CTYPE* __AllocCArray_##CTYPE; -%enddef - - %define DEFINE_EXTERNAL_CLASS(CTYPE, CSTYPE) %typemap(cstype) (CTYPE*) "CSTYPE" %typemap(csin) (CTYPE*) "CSTYPE.getCPtr($csinput)" @@ -301,65 +196,206 @@ } %enddef -%define CSHARP_ARRAYS_PINNED(CTYPE, CSTYPE) -%typemap(ctype) CTYPE PINNED[], CTYPE PINNED_STATIC[] "CTYPE*" -%typemap(imtype) CTYPE PINNED[], CTYPE PINNED_STATIC[] "global::System.IntPtr" -%typemap(cstype) CTYPE PINNED[], CTYPE PINNED_STATIC[] "CSTYPE[]" +%{ +typedef struct { + int32_t Count; + int32_t ItemSize; + void *pArray; +} ArrayWithSize; +%} + +%define PRIMITIVE_ARRAYS_INOUT(CTYPE, CSTYPE) +%typemap(ctype) (int nList, CTYPE *pList) "ArrayWithSize*" +%typemap(imtype) (int nList, CTYPE *pList) "in $modulePINVOKE.ArrayWithSize" +%typemap(cstype) (int nList, CTYPE *pList) "CSTYPE[]" +%typemap(in) (int nList, CTYPE *pList) %{ + $1 = static_cast<$1_ltype>($input->Count); + $2 = ($2_ltype)$input->pArray; +%} %typemap(csin, - pre=" GCHandle swig_handleTo_$csinput = GCHandle.Alloc($csinput, GCHandleType.Pinned); - try {", - terminator=" } finally { - swig_handleTo_$csinput.Free(); - GC.KeepAlive(this); - }" -) CTYPE PINNED[] "swig_handleTo_$csinput.AddrOfPinnedObject()" + pre=" GCHandle h$csinput = GCHandle.Alloc($csinput, GCHandleType.Pinned); + var temp$csinput = new $modulePINVOKE.ArrayWithSize($csinput?.Length ?? 0, sizeof(CSTYPE), h$csinput.AddrOfPinnedObject());", + post=" h$csinput.Free();" +) (int nList, CTYPE *pList) "temp$csinput" +/* list of primitives out - list not freed */ +%typemap(ctype) (int *nLen, CTYPE **pList) "ArrayWithSize*" +%typemap(imtype) (int *nLen, CTYPE **pList) "ref $modulePINVOKE.ArrayWithSize" +%typemap(cstype) (int *nLen, CTYPE **pList) "out CSTYPE[]" +%typemap(in) (int *nLen, CTYPE **pList) %{ + $input->ItemSize = static_cast(sizeof(CTYPE)); + $*1_ltype count$input = static_cast<$*1_ltype>($input->Count); + $1 = &count$input; + $2 = ($2_ltype)&$input->pArray; +%} +%typemap(argout) (int *nLen, CTYPE **pList) %{ + $input->Count = static_cast(count$input); +%} +%apply (int *nLen, CTYPE **pList) {(int *nLen, CTYPE **pList_free)}; %typemap(csin, - pre=" GCHandle swig_handleTo_$csinput = GCHandle.Alloc($csinput, GCHandleType.Pinned); - try {", - terminator=" } finally { - swig_handleTo_$csinput.Free(); - }" -) CTYPE PINNED_STATIC[] "swig_handleTo_$csinput.AddrOfPinnedObject()" -%typemap(in) CTYPE PINNED[], CTYPE PINNED_STATIC[] "$1 = ($1_ltype)$input;" -%typemap(freearg) CTYPE PINNED[], CTYPE PINNED_STATIC[] "" -%typemap(argout) CTYPE PINNED[], CTYPE PINNED_STATIC[] "" -%enddef // CSHARP_ARRAYS_PINNED - -%define CSHARP_OBJECT_ARRAYS_PINNED(CTYPE, CSTYPE) -%typemap(ctype) CTYPE OBJPTRS[], CTYPE OBJPTRS_STATIC[] "CTYPE**" -%typemap(imtype) CTYPE OBJPTRS[], CTYPE OBJPTRS_STATIC[] "global::System.IntPtr" -%typemap(cstype) CTYPE OBJPTRS[], CTYPE OBJPTRS_STATIC[] "CSTYPE[]" + pre=" var temp$csinput = default($modulePINVOKE.ArrayWithSize);", + terminator=" $csinput = temp$csinput.ToPrimitiveArray();" +) (int *nLen, CTYPE **pList) "ref temp$csinput" +/* list of primitives out - list freed */ %typemap(csin, - pre=" IntPtr swig_ptrs_ptr_$csinput = System.IntPtr.Zero; - GCHandle swig_handleTo_ptrs_$csinput = new GCHandle(); - if ($csinput != null) { - IntPtr[] swig_ptrs_$csinput = new IntPtr[$csinput.Length]; - for (int i = 0; i < $csinput.Length; i++) swig_ptrs_$csinput[i] = CSTYPE.getCPtr($csinput[i]).Handle; - swig_handleTo_ptrs_$csinput = GCHandle.Alloc(swig_ptrs_$csinput, GCHandleType.Pinned); - swig_ptrs_ptr_$csinput = swig_handleTo_ptrs_$csinput.AddrOfPinnedObject(); - } - try {", - terminator=" } finally { - if ($csinput != null) swig_handleTo_ptrs_$csinput.Free(); - GC.KeepAlive(this); - }" -) CTYPE OBJPTRS[] "swig_ptrs_ptr_$csinput" + pre=" var temp$csinput = default($modulePINVOKE.ArrayWithSize);", + post=" $csinput = temp$csinput.ToPrimitiveArray(); + $module.CPLMemDestroy(temp$csinput.pArray);" +) (int *nLen, CTYPE **pList_free) "ref temp$csinput" +%apply (int *nLen, CTYPE **pList) {(int *nLen, const CTYPE **pList)}; +%apply (int *nLen, CTYPE **pList_free) {(int *nLen, const CTYPE **pList_free)}; +%enddef //PRIMITIVE_ARRAYS_INOUT + +%define VALUE_LIST_INOUT(CTYPE, CSTYPE) +%typemap(ctype) (int nList, CTYPE *pList) "ArrayWithSize*" +%typemap(imtype) (int nList, CTYPE *pList) "in $modulePINVOKE.ArrayWithSize" +%typemap(cstype) (int nList, CTYPE *pList) "CSTYPE[]" +%typemap(in) (int nList, CTYPE *pList) %{ + $1 = static_cast<$1_ltype>($input->Count); + $2 = ($2_ltype)$input->pArray; +%} +%typemap(csin, + pre=" using (var temp$csinput = $modulePINVOKE.ArrayHelper.CreateByValue($csinput, CSTYPE.GetNativeSizeOf(), CSTYPE.getCPtr)) {", + terminator=" }" +) (int nList, CTYPE *pList) "temp$csinput.GetArrayWithSize()" +%extend CTYPE { + static int GetNativeSizeOf() { + return static_cast(sizeof(CTYPE)); + } +} +/* list of values out - elements not owned - list not freed */ +%typemap(ctype) (int *nList, CTYPE **pList) "ArrayWithSize*" +%typemap(imtype) (int *nList, CTYPE **pList) "ref $modulePINVOKE.ArrayWithSize" +%typemap(cstype) (int *nList, CTYPE **pList) "out CSTYPE[]" +%typemap(in) (int *nList, CTYPE **pList) %{ + $input->ItemSize = static_cast(sizeof(CTYPE)); + $*1_ltype count$input = static_cast<$*1_ltype>($input->Count); + $1 = &count$input; + $2 = ($2_ltype)&$input->pArray; +%} +%typemap(argout) (int *nList, CTYPE **pList) %{ + $input->Count = static_cast(count$input); +%} %typemap(csin, - pre=" IntPtr swig_ptrs_ptr_$csinput = System.IntPtr.Zero; - GCHandle swig_handleTo_ptrs_$csinput = new GCHandle(); - if ($csinput != null) { - IntPtr[] swig_ptrs_$csinput = new IntPtr[$csinput.Length]; - for (int i = 0; i < $csinput.Length; i++) swig_ptrs_$csinput[i] = CSTYPE.getCPtr($csinput[i]).Handle; - swig_handleTo_ptrs_$csinput = GCHandle.Alloc(swig_ptrs_$csinput, GCHandleType.Pinned); - swig_ptrs_ptr_$csinput = swig_handleTo_ptrs_$csinput.AddrOfPinnedObject(); + pre=" var temp$csinput = default($modulePINVOKE.ArrayWithSize);", + terminator=" $csinput = temp$csinput.ToValueArray(p => new CSTYPE(p, false, ThisOwn_false()));" +) (int* nList, CTYPE **pList) "ref temp$csinput" +%enddef //VALUE_LIST_INOUT + +%define OBJECT_LIST_INOUT(CTYPE, CSTYPE) +%typemap(ctype) (int object_list_count, CTYPE **poObjects) "ArrayWithSize*" +%typemap(imtype) (int object_list_count, CTYPE **poObjects) "in $modulePINVOKE.ArrayWithSize" +%typemap(cstype) (int object_list_count, CTYPE **poObjects) "CSTYPE[]" +%typemap(in) (int object_list_count, CTYPE **poObjects) %{ + $1 = static_cast<$1_ltype>($input->Count); + $2 = ($2_ltype)$input->pArray; +%} +%typemap(csin, + pre=" using (var temp$csinput = $modulePINVOKE.ArrayHelper.CreateByReference($csinput, CSTYPE.getCPtr)) {", + terminator=" }" +) (int object_list_count, CTYPE **poObjects) "temp$csinput.GetArrayWithSize()" +/* list of objects out - elements not owned - list not freed */ +%typemap(ctype) (int *object_list_count, CTYPE **poObjects) "ArrayWithSize*" +%typemap(imtype) (int *object_list_count, CTYPE **poObjects) "ref $modulePINVOKE.ArrayWithSize" +%typemap(cstype) (int *object_list_count, CTYPE **poObjects) "out CSTYPE[]" +%typemap(in) (int *object_list_count, CTYPE **poObjects) %{ + $input->ItemSize = static_cast(sizeof(void*)); + $*1_ltype count$input = static_cast<$*1_ltype>($input->Count); + $1 = &count$input; + $2 = ($2_ltype)&$input->pArray; +%} +%typemap(argout) (int *object_list_count, CTYPE **poObjects) %{ + $input->Count = static_cast(count$input); +%} +%typemap(csin, + pre=" var temp$csinput = default($modulePINVOKE.ArrayWithSize);", + terminator=" $csinput = temp$csinput.ToReferenceArray(p => new CSTYPE(p, false, ThisOwn_false()));" +) (int* object_list_count, CTYPE **poObjects) "ref temp$csinput" +%enddef //OBJECT_LIST_INOUT + +%pragma(csharp) imclasscode=%{ +internal readonly ref struct ArrayWithSize { + public readonly int Count; + public readonly int ItemSize; + public readonly IntPtr pArray; + + public ArrayWithSize(int count, int itemSize, IntPtr p) { + Count = count; + ItemSize = itemSize; + pArray = p; + } + + public unsafe TVal[] ToPrimitiveArray() where TVal : unmanaged { + if (pArray == IntPtr.Zero || Count <= 0 || ItemSize != sizeof(TVal)) return new TVal[0]; + TVal[] result = new TVal[Count]; + long toCopy = (long)Count * ItemSize; + fixed (TVal* pResult = result) + Buffer.MemoryCopy(pArray.ToPointer(), pResult, toCopy, toCopy); + return result; + } + + public TVal[] ToValueArray(Func objectCreator) + => FromUnmanaged(objectCreator, byValue: true); + + public TRef[] ToReferenceArray(Func objectCreator) + => FromUnmanaged(objectCreator, byValue: false); + + private T[] FromUnmanaged(Func objectCreator, bool byValue) { + if (pArray == IntPtr.Zero || Count <= 0 || ItemSize <= 0) return new T[0]; + T[] result = new T[Count]; + IntPtr pItem = pArray; + for (int i = 0; i < Count; i++, pItem = IntPtr.Add(pItem, ItemSize)) { + IntPtr pCurrent = byValue ? pItem : Marshal.ReadIntPtr(pItem); + result[i] = pCurrent == IntPtr.Zero ? default(T) : objectCreator(pCurrent); } - try {", - terminator=" } finally { - if ($csinput != null) swig_handleTo_ptrs_$csinput.Free(); - }" -) CTYPE OBJPTRS_STATIC[] "swig_ptrs_ptr_$csinput" - -%typemap(in) CTYPE OBJPTRS[], CTYPE OBJPTRS_STATIC[] "$1 = ($1_ltype)$input;" -%typemap(freearg) CTYPE OBJPTRS[], CTYPE OBJPTRS_STATIC[] "" -%typemap(argout) CTYPE OBJPTRS[], CTYPE OBJPTRS_STATIC[] "" -%enddef // CSHARP_OBJECT_ARRAYS_PINNED + return result; + } +} +internal class ArrayHelper : IDisposable { + private IntPtr m_ArrayHandle; + private T[] Objects { get; } + public int Count { get; } + public int ItemSize { get; } + public ArrayWithSize GetArrayWithSize() => new ArrayWithSize(Count, ItemSize, m_ArrayHandle); + + private ArrayHelper(T[] array, int itemSize) { + ItemSize = itemSize; + Objects = array; + if (Objects == null || Objects.Length == 0) return; + Count = Objects.Length; + IntPtr memSize = new IntPtr(checked((long)Count * ItemSize)); + m_ArrayHandle = Marshal.AllocHGlobal(memSize); + } + + public unsafe static ArrayHelper CreateByValue(T[] array, int itemSize, Func handleGetter) { + var helper = itemSize > 0 ? new ArrayHelper(array, itemSize) + : throw new ArgumentOutOfRangeException(nameof(itemSize), "Must be a positive integer."); + + byte* pDest = (byte*)helper.m_ArrayHandle; + for (int i = 0; i < helper.Count; i++, pDest += itemSize) { + IntPtr handle = handleGetter(helper.Objects[i]).Handle; + if (handle == IntPtr.Zero) + throw new NullReferenceException("By-value arrays cannot contain null elements."); + Buffer.MemoryCopy(handle.ToPointer(), pDest, itemSize, itemSize); + } + return helper; + } + + public unsafe static ArrayHelper CreateByReference(T[] array, Func handleGetter) { + var helper = new ArrayHelper(array, IntPtr.Size); + IntPtr* pDest = (IntPtr*)helper.m_ArrayHandle; + for (int i = 0; i < helper.Count; i++) { + //Should null reference elements be allowed?? + pDest[i] = handleGetter(helper.Objects[i]).Handle; + } + return helper; + } + + public void Dispose() { + IntPtr arrayHandle = System.Threading.Interlocked.Exchange(ref m_ArrayHandle, IntPtr.Zero); + if (arrayHandle != IntPtr.Zero) + System.Runtime.InteropServices.Marshal.FreeHGlobal(arrayHandle); + System.GC.SuppressFinalize(this); + } + ~ArrayHelper() => Dispose(); +} +%} diff --git a/swig/include/csharp/typemaps_csharp.i b/swig/include/csharp/typemaps_csharp.i index 2e512b6aee87..f72f1425b90e 100644 --- a/swig/include/csharp/typemaps_csharp.i +++ b/swig/include/csharp/typemaps_csharp.i @@ -16,47 +16,6 @@ %include "arrays_csharp.i" %include "csharp_strings.i" -/* CSHARP TYPEMAPS */ - -%typemap(csdispose) SWIGTYPE %{ - ~$csclassname() { - Dispose(); - } -%} - -%typemap(csdispose_derived) SWIGTYPE %{ - ~$csclassname() { - Dispose(); - } -%} - -%typemap(csdisposing, methodname="Dispose", methodmodifiers="public", parameters="") SWIGTYPE { - lock(this) { - if (swigCPtr.Handle != global::System.IntPtr.Zero) { - if (swigCMemOwn) { - swigCMemOwn = false; - $imcall; - } - swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); - } - global::System.GC.SuppressFinalize(this); - } - } - -%typemap(csdisposing_derived, methodname="Dispose", methodmodifiers="public", parameters="") SWIGTYPE { - lock(this) { - if (swigCPtr.Handle != global::System.IntPtr.Zero) { - if (swigCMemOwn) { - swigCMemOwn = false; - $imcall; - } - swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); - } - global::System.GC.SuppressFinalize(this); - base.Dispose(); - } - } - %apply (int) {VSI_RETVAL}; %fragment("OGRErrMessages","header") %{ @@ -100,22 +59,12 @@ OGRErrMessages( int rc ) { } -%typemap(in) (tostring argin) (string str) -{ - /* %typemap(in) (tostring argin) */ - $1 = ($1_ltype)$input; -} - /* GDAL Typemaps */ -%typemap(out) IF_FALSE_RETURN_NONE %{ $result = $1; %} -%typemap(ctype) IF_FALSE_RETURN_NONE "int" -%typemap(imtype) IF_FALSE_RETURN_NONE "int" -%typemap(cstype) IF_FALSE_RETURN_NONE "int" -%typemap(csout, excode=SWIGEXCODE) IF_FALSE_RETURN_NONE { - int res = $imcall;$excode - return res; -} +%apply (char*) {(tostring argin)}; +%apply (long) {(IF_FALSE_RETURN_NONE)}; +%apply (long long) {GIntBig}; +%apply (unsigned long long) {GUIntBig}; %typemap(out) IF_ERROR_RETURN_NONE %{ $result = $1; %} @@ -129,40 +78,10 @@ OGRErrMessages( int rc ) { /* %typemap(in) (type *optional_##CTYPE) */ $1 = ($1_type)$input; } -%enddef +%enddef //OPTIONAL_POD OPTIONAL_POD(int, int); -/* - * Typemap for GIntBig (int64) - */ - -%typemap(ctype, out="GIntBig") GIntBig %{GIntBig%} -%typemap(imtype, out="long") GIntBig "long" -%typemap(cstype) GIntBig %{long%} -%typemap(in) GIntBig %{ $1 = $input; %} -%typemap(out) GIntBig %{ $result = $1; %} -%typemap(csin) GIntBig "$csinput" -%typemap(csout, excode=SWIGEXCODE) GIntBig { - long res = $imcall;$excode - return res; -} - -/* - * Typemap for GUIntBig (uint64) - */ - -%typemap(ctype, out="GUIntBig") GUIntBig %{GUIntBig%} -%typemap(imtype, out="ulong") GUIntBig "ulong" -%typemap(cstype) GUIntBig %{ulong%} -%typemap(in) GUIntBig %{ $1 = $input; %} -%typemap(out) GUIntBig %{ $result = $1; %} -%typemap(csin) GUIntBig "$csinput" -%typemap(csout, excode=SWIGEXCODE) GUIntBig { - ulong res = $imcall;$excode - return res; -} - /* * Typemap for size_t native_size */ @@ -180,237 +99,98 @@ OPTIONAL_POD(int, int); * Typemap for PINNED arrays */ -CSHARP_ARRAYS_PINNED(GUIntBig, uint) -CSHARP_ARRAYS_PINNED(int, int) -CSHARP_OBJECT_ARRAYS_PINNED(GDALRasterBandShadow, Band) - -%typemap(imtype, out="IntPtr") int *intList "int[]" -%typemap(cstype) int *intList %{int[]%} -%typemap(in) int *intList %{ $1 = ($1_ltype)$input; %} -%typemap(out) int *intList %{ $result = $1; %} -%typemap(csout, excode=SWIGEXCODE) int *intList { - /* %typemap(csout) int *intList */ - IntPtr cPtr = $imcall; - int[] ret = new int[count]; - if (count > 0) { - System.Runtime.InteropServices.Marshal.Copy(cPtr, ret, 0, count); - } - $excode - return ret; -} - -%typemap(imtype, out="IntPtr") double *doubleList "double[]" -%typemap(cstype) double *doubleList %{double[]%} -%typemap(in) double *doubleList %{ $1 = ($1_ltype)$input; %} -%typemap(out) double *doubleList %{ $result = $1; %} -%typemap(csout, excode=SWIGEXCODE) double *doubleList { - /* %typemap(csout) int *intList */ +PRIMITIVE_ARRAYS_INOUT(GIntBig, long) +PRIMITIVE_ARRAYS_INOUT(GUIntBig, ulong) +PRIMITIVE_ARRAYS_INOUT(char, byte) +PRIMITIVE_ARRAYS_INOUT(int, int) +PRIMITIVE_ARRAYS_INOUT(double, double) +OBJECT_LIST_INOUT(GDALDatasetShadow, Dataset) +OBJECT_LIST_INOUT(GDALRasterBandShadow, Band) +OBJECT_LIST_INOUT(GDALEDTComponentHS, EDTComponent) +OBJECT_LIST_INOUT(OGRLayerShadow, OSGeo.OGR.Layer) + +%define %NUMBER_VALUE_LIST(CTYPE, CSTYPE) + +%typemap(imtype, out="IntPtr") CTYPE *CSTYPE##List "CSTYPE[]" +%typemap(cstype) CTYPE *CSTYPE##List %{CSTYPE[]%} +%typemap(in) CTYPE *CSTYPE##List %{ $1 = ($1_ltype)$input; %} +%typemap(out) CTYPE *CSTYPE##List %{ $result = $1; %} +%typemap(csout, excode=SWIGEXCODE) CTYPE *CSTYPE##List { + /* %typemap(csout) CTYPE *CSTYPE##List */ IntPtr cPtr = $imcall; - double[] ret = new double[count]; + CSTYPE[] ret = new CSTYPE[count]; if (count > 0) { - System.Runtime.InteropServices.Marshal.Copy(cPtr, ret, 0, count); + System.Runtime.InteropServices.Marshal.Copy(cPtr, ret, 0, count); } $excode return ret; } +%enddef //%NUMBER_VALUE_LIST -/* - * Typemap for double argout[ANY]. - */ -%typemap(imtype) (double argout[ANY]) "double[]" -%typemap(cstype) (double argout[ANY]) "double[]" -%typemap(csin) (double argout[ANY]) "$csinput" - -%typemap(in) (double argout[ANY]) -{ - /* %typemap(in) (double argout[ANY]) */ - $1 = ($1_ltype)$input; -} - -%typemap(in,numinputs=0) ( double *argout[ANY]) (double *argout[$dim0]) -{ - /* %typemap(in,numinputs=0) (double *argout[ANY]) */ - $1 = (double**)&argout; -} -%typemap(argout) ( double *argout[ANY]) -{ - /* %typemap(argout) (double *argout[ANY]) */ - -} -%typemap(freearg) (double *argout[ANY]) -{ - /* %typemap(freearg) (double *argout[ANY]) */ - -} - -%apply double argout[ANY] {double *inout} +%NUMBER_VALUE_LIST(GByte, byte); // (GByte *byteList) +%NUMBER_VALUE_LIST(int, int); // (int *intList) +%NUMBER_VALUE_LIST(GIntBig, long); // (GIntBig *longList) +%NUMBER_VALUE_LIST(double, double); // (double *doubleList) /* - * Typemap for double argin[ANY]. + * Macro for generating CTYPE typemaps for *argout[ANY], argout[ANY], + * argin[ANY], and inout[ANY] */ -%typemap(imtype) (double argin[ANY]) "double[]" -%typemap(cstype) (double argin[ANY]) "double[]" -%typemap(csin) (double argin[ANY]) "$csinput" +%define %FIXED_SIZE_ARRAYS(CTYPE, CSTYPE) -%typemap(in) (double argin[ANY]) -{ - /* %typemap(in) (double argin[ANY]) */ - $1 = ($1_ltype)$input; +%typemap(ctype) (CTYPE *argout[ANY]) "CTYPE*" +%typemap(imtype) (CTYPE *argout[ANY]) "CSTYPE[]" +%typemap(cstype) (CTYPE *argout[ANY]) "out CSTYPE[]" +%typemap(csin, pre="$csinput = new CSTYPE[$1_dim0];") (CTYPE *argout[ANY]) "$csinput" +%typemap(in) (CTYPE *argout[ANY]) { + /* %typemap(in) (CTYPE *argout[ANY]) */ + $*1_ltype tmp$1_name = NULL; + $1 = ($1_ltype)&tmp$1_name; } - -/* - * Typemap for int argin[ANY]. - */ - -%typemap(imtype) (int argin[ANY]) "int[]" -%typemap(cstype) (int argin[ANY]) "int[]" -%typemap(csin) (int argin[ANY]) "$csinput" - -%typemap(in) (int argin[ANY]) -{ - /* %typemap(in) (int argin[ANY]) */ - $1 = ($1_ltype)$input; +%typemap(argout) (CTYPE *argout[ANY]) { + /* %typemap(argout) (CTYPE *argout[ANY]) */ + memcpy($input, *$1, $1_dim0 * sizeof(CTYPE)); } - -/* - * Typemap for double inout[ANY]. - */ - -%typemap(imtype) (double inout[ANY]) "double[]" -%typemap(cstype) (double inout[ANY]) "double[]" -%typemap(csin) (double inout[ANY]) "$csinput" - -%typemap(in) (double inout[ANY]) -{ - /* %typemap(in) (double inout[ANY]) */ - $1 = ($1_ltype)$input; +%typemap(freearg) (CTYPE *argout[ANY]) { + /* %typemap(freearg) (CTYPE *argout[ANY]) */ + CPLFree(*$1); } -%apply (double inout[ANY]) {double *pList}; - -/* - * Typemap for int inout[ANY]. - */ - -%typemap(imtype) (int inout[ANY]) "int[]" -%typemap(cstype) (int inout[ANY]) "int[]" -%typemap(csin) (int inout[ANY]) "$csinput" - -%typemap(in) (int inout[ANY]) -{ - /* %typemap(in) (int inout[ANY]) */ +%typemap(ctype) CTYPE inout[ANY] "CTYPE*" +%typemap(imtype) CTYPE inout[ANY] "CSTYPE[]" +%typemap(cstype) CTYPE inout[ANY] "CSTYPE[]" +%typemap(in) CTYPE inout[ANY] { + /* %typemap(in) CTYPE inout[ANY] */ $1 = ($1_ltype)$input; } +%typemap(csin, pre=" + if($csinput is null) throw new ArgumentNullException(\"$csinput\"); + if($csinput.Length < $1_dim0) throw new ArgumentException(\"Array must be at least $1_dim0 elements long.\", \"$csinput\");" +) CTYPE inout[ANY] "$csinput" -%apply (int inout[ANY]) {int *pList}; - -/* - * Typemap for double *defaultval. - */ - -%typemap(imtype) (double *defaultval) "ref double" -%typemap(cstype) (double *defaultval) "ref double" -%typemap(csin) (double *defaultval) "ref $csinput" +%apply CTYPE inout [ANY] {CTYPE argin [ANY], CTYPE argout[ANY]}; +%enddef // %FIXED_SIZE_ARRAYS -%typemap(in) (double *defaultval) -{ - /* %typemap(in) (double inout[ANY]) */ - $1 = ($1_ltype)$input; -} +%FIXED_SIZE_ARRAYS(int, int); +%FIXED_SIZE_ARRAYS(double, double); /* - * Typemap for out double. + * Typemap for 'out double'. */ - -%typemap(imtype) (double *OUTPUT), (double *val), (double *min), (double *max), (double *mean), (double *stddev) "out double" -%typemap(cstype) (double *OUTPUT), (double *val), (double *min), (double *max), (double *mean), (double *stddev) "out double" -%typemap(csin) (double *OUTPUT), (double *val), (double *min), (double *max), (double *mean), (double *stddev) "out $csinput" - -%typemap(in) (double *OUTPUT), (double *val), (double *min), (double *max), (double *mean), (double *stddev) -{ - /* %typemap(in) (double *val) */ - $1 = ($1_ltype)$input; -} +%apply (double *OUTPUT) {(double *val), (double *min), (double *max), (double *mean), (double *stddev)}; /* * Typemap for 'out int'. */ - -%typemap(imtype) (int *hasval) "out int" -%typemap(cstype) (int *hasval) "out int" -%typemap(csin) (int *hasval) "out $csinput" - -%typemap(in) (int *hasval) -{ - /* %typemap(in) (int *hasval) */ - $1 = ($1_ltype)$input; -} - -%apply (int *hasval) {int *nLen}; -%apply (int *hasval) {int *pnBytes}; - -/* - * Typemap for int **array_argout. - */ - -%typemap(imtype) (int **array_argout) "out int[]" -%typemap(cstype) (int **array_argout) "out int[]" -%typemap(csin) (int **array_argout) "out $csinput" - -%typemap(in) (int **array_argout) -{ - /* %typemap(in) (int **array_argout) */ - $1 = ($1_ltype)$input; -} - -%apply (int **array_argout) {int **pList}; - -/* - * Typemap for double **array_argout. - */ - -%typemap(imtype) (double **array_argout) "out double[]" -%typemap(cstype) (double **array_argout) "out double[]" -%typemap(csin) (double **array_argout) "out $csinput" - -%typemap(in) (double **array_argout) -{ - /* %typemap(in) (double **array_argout) */ - $1 = ($1_ltype)$input; -} - -%apply (double **array_argout) {double **pList}; +%apply (int *OUTPUT) {int *hasval, int *nLen, int *pnBytes}; /* * Typemap for void* user_data for SetErrorHandler. * Note: The user should implement marshaling their own data to IntPtr. */ -%typemap(imtype) (void* user_data) "IntPtr" -%typemap(cstype) (void* user_data) "IntPtr" -%typemap(csin) (void* user_data) "$csinput" - -/****************************************************************************** - * GDAL raster R/W support * - *****************************************************************************/ - -%typemap(imtype, out="IntPtr") void *buffer_ptr "IntPtr" -%typemap(cstype) void *buffer_ptr %{IntPtr%} -%typemap(in) void *buffer_ptr %{ $1 = ($1_ltype)$input; %} -%typemap(out) void *buffer_ptr %{ $result = $1; %} -%typemap(csin) void *buffer_ptr "$csinput" -%typemap(csout, excode=SWIGEXCODE) void *buffer_ptr { - IntPtr ret = $imcall;$excode - return ret; -} -%typemap(csvarout, excode=SWIGEXCODE2) (void *buffer_ptr) %{ - get { - IntPtr ret = $imcall;$excode - return ret; - } %} - -%apply (void *buffer_ptr) {GByte*, VSILFILE*}; +%apply (void *VOID_INT_PTR) {void* user_data, void *buffer_ptr, GByte*, VSILFILE*}; %csmethodmodifiers CPLMemDestroy "internal"; %inline %{ @@ -420,87 +200,98 @@ CSHARP_OBJECT_ARRAYS_PINNED(GDALRasterBandShadow, Band) } %} +%define %DELEGATE_TYPEMAP(CTYPE, CSTYPE) + +%typemap(ctype) (CTYPE) "CTYPE" +%typemap(imtype) (CTYPE) "CSTYPE" +%typemap(cstype) (CTYPE) "CSTYPE" +%typemap(csin) (CTYPE) "$csinput" +%typemap(in) (CTYPE) %{ $1 = $input; %} +%typemap(out) (CTYPE) %{ $result = $1; %} +%typemap(csvarout, excode=SWIGEXCODE2) (CTYPE) %{ + get { + CSTYPE ret = $imcall;$excode + return ret; + } %} +%typemap(csout, excode=SWIGEXCODE) (CTYPE) %{ + CSTYPE ret = $imcall;$excode + return ret; +%} +%enddef //DELEGATE_TYPEMAP + /****************************************************************************** - * ErrorHandler callback support * + * CPLErrorHandler callback support * *****************************************************************************/ %pragma(csharp) modulecode="public delegate void GDALErrorHandlerDelegate(int eclass, int code, IntPtr msg);" -%typemap(imtype) (CPLErrorHandler) "$module.GDALErrorHandlerDelegate" -%typemap(cstype) (CPLErrorHandler) "$module.GDALErrorHandlerDelegate" -%typemap(csin) (CPLErrorHandler) "$csinput" -%typemap(in) (CPLErrorHandler) %{ $1 = ($1_ltype)$input; %} +%DELEGATE_TYPEMAP(CPLErrorHandler, $module.GDALErrorHandlerDelegate); + +/****************************************************************************** + * GDALTransformerFunc typemaps * + *****************************************************************************/ +%pragma(csharp) modulecode="public delegate bool GDALTransformerFuncDelegate(IntPtr pTransformerArg, int bDstToSrc, int nPointCount, IntPtr x, IntPtr y, IntPtr z, IntPtr panSuccess);" +%DELEGATE_TYPEMAP(GDALTransformerFunc, $module.GDALTransformerFuncDelegate); /****************************************************************************** * GDALProgressFunc typemaps * *****************************************************************************/ %pragma(csharp) modulecode="public delegate int GDALProgressFuncDelegate(double Complete, IntPtr Message, IntPtr Data);" +%DELEGATE_TYPEMAP(GDALProgressFunc, $module.GDALProgressFuncDelegate); -%typemap(imtype) (GDALProgressFunc callback) "$module.GDALProgressFuncDelegate" -%typemap(cstype) (GDALProgressFunc callback) "$module.GDALProgressFuncDelegate" -%typemap(csin) (GDALProgressFunc callback) "$csinput" -%typemap(csvarout, excode=SWIGEXCODE2) (GDALProgressFunc callback) %{ - get { - Gdal.GDALProgressFuncDelegate ret = $imcall;$excode - return ret; - } %} -%typemap(in) (GDALProgressFunc callback) %{ $1 = ($1_ltype)$input; %} %apply (char*) {(void* callback_data)}; -%ignore SWIGTYPE_p_GDALProgressFunc; - /****************************************************************************** * GDALGetNextFeature typemaps * *****************************************************************************/ -%apply (double *defaultval) {double* pdfProgressPct}; - -%typemap(imtype) (OGRLayerShadow **ppoBelongingLayer) "ref IntPtr" -%typemap(cstype) (OGRLayerShadow **ppoBelongingLayer) "ref IntPtr" -%typemap(csin) (OGRLayerShadow **ppoBelongingLayer) "ref $csinput" - -/****************************************************************************** - * Band.AdviseRead and Dataset.AdviseRead typemaps * - *****************************************************************************/ -%apply (int *INOUT) {int *buf_xsize, int *buf_ysize}; +%typemap(imtype) (OGRLayerShadow **ppoBelongingLayer) "ref IntPtr" +%typemap(cstype) (OGRLayerShadow **ppoBelongingLayer) "out OSGeo.OGR.Layer" +%typemap(csin, + pre=" IntPtr p$csinput = IntPtr.Zero;", + post=" $csinput = p$csinput == IntPtr.Zero ? null : new OSGeo.OGR.Layer(p$csinput, false, ThisOwn_false());" +) (OGRLayerShadow **ppoBelongingLayer) "ref p$csinput" /****************************************************************************** * SpatialReference.FindMatches * *****************************************************************************/ -%apply (int *hasval) {int *nvalues}; +%apply (int *nLen, int **pList_free) {(int* confidence_values, int** ppanMatchConfidence )}; %typemap(imtype, out="IntPtr") OSRSpatialReferenceShadow** FindMatches "SpatialReference[]" %typemap(cstype) OSRSpatialReferenceShadow** FindMatches %{SpatialReference[]%} -%typemap(imtype) int** confidence_values "out IntPtr" -%typemap(cstype) int** confidence_values %{out int[]%} -%typemap(csin) int** confidence_values "out confValPtr" -%typemap(in) (int** confidence_values) -{ - /* %typemap(in) (int** confidence_values) */ - $1 = ($1_ltype)$input; -} %typemap(csout, excode=SWIGEXCODE) OSRSpatialReferenceShadow** FindMatches { /* %typemap(csout) OSRSpatialReferenceShadow** FindMatches */ - IntPtr confValPtr; IntPtr cPtr = $imcall; - IntPtr objPtr; - SpatialReference[] ret = new SpatialReference[nvalues]; - confidence_values = (confValPtr == IntPtr.Zero) ? null : new int[nvalues]; - if (nvalues > 0) { - for(int cx = 0; cx < nvalues; cx++) { - objPtr = System.Runtime.InteropServices.Marshal.ReadIntPtr(cPtr, cx * System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr))); - /* SpatialReference will take ownership of the unmanaged memory and will call OSRRelease() when the object is disposed. - Therefore, OSRFreeSRSArray() is not called; only CPLFree() is used to release the array itself. */ - ret[cx]= (objPtr == IntPtr.Zero) ? null : new SpatialReference(objPtr, true, null); - if (confValPtr != IntPtr.Zero) { - confidence_values[cx] = System.Runtime.InteropServices.Marshal.ReadInt32(confValPtr, cx * System.Runtime.InteropServices.Marshal.SizeOf(typeof(Int32))); - } - - } - } + $excode + var srsArray = new $modulePINVOKE.ArrayWithSize(tempconfidence_values.Count, IntPtr.Size, cPtr); + SpatialReference[] ret = srsArray.ToReferenceArray(p => new SpatialReference(p, true, ThisOwn_true())); if (cPtr != IntPtr.Zero) { $modulePINVOKE.CPLMemDestroy(cPtr); } - if (confValPtr != IntPtr.Zero) { - $modulePINVOKE.CPLMemDestroy(confValPtr); - } - $excode return ret; } + +/*************************************************** + * Typemaps converts a OGRCodedValue to/from a * + * Dictionary * + ***************************************************/ + +%typemap(ctype) const OGRCodedValue* "OGRCodedValue*" +%typemap(imtype, out="IntPtr") const OGRCodedValue* "IntPtr[]" +%typemap(in) const OGRCodedValue* %{ $1 = $input; %} +%typemap(out) const OGRCodedValue* %{ $result = $1; %} +%typemap(cstype) const OGRCodedValue* "System.Collections.Generic.Dictionary" +%typemap(csin, cshin="$csinput", + pre=" using (var temp$csinput = new $modulePINVOKE.StringListMarshal($csinput)) { ", + terminator=" }") + const OGRCodedValue* + "temp$csinput._ar" + +%typemap(csout, excode=SWIGEXCODE) const OGRCodedValue* +{ + /* %typemap(csout) const OGRCodedValue* */ + IntPtr pEnum = $imcall; + $excode + var kvps = $modulePINVOKE.StringListMarshal.DecodeKeyValuePairArray(pEnum); + var dict = new System.Collections.Generic.Dictionary(kvps.Length); + foreach (var kvp in kvps) + dict.Add(kvp.Key, kvp.Value); + return dict; +} diff --git a/swig/include/gdal.i b/swig/include/gdal.i index 215f0e5fa64d..f162554dd065 100644 --- a/swig/include/gdal.i +++ b/swig/include/gdal.i @@ -25,7 +25,7 @@ %include swig_csharp_extensions.i #endif -#ifndef SWIGJAVA +#if !defined(SWIGJAVA) && !defined(SWIGCSHARP) %feature ("compactdefaultargs"); #endif @@ -492,6 +492,8 @@ struct GDAL_GCP { }; /* GDAL_GCP */ %apply Pointer NONNULL {GDAL_GCP *gcp}; + +#if !defined(SWIGCSHARP) %inline %{ double GDAL_GCP_GCPX_get( GDAL_GCP *gcp ) { @@ -541,64 +543,64 @@ void GDAL_GCP_Id_set( GDAL_GCP *gcp, const char * pszId ) { gcp->pszId = CPLStrdup(pszId); } %} //%inline - -#if defined(SWIGCSHARP) -%inline %{ -/* Duplicate, but transposed names for C# because -* the C# module outputs backwards names -*/ -double GDAL_GCP_get_GCPX( GDAL_GCP *gcp ) { +#else +/* + * SWIG does not need these functions to be inlined to use + * them from C# properties. + */ +%{ +double GDAL_GCP_GCPX_get( GDAL_GCP *gcp ) { return gcp->dfGCPX; } -void GDAL_GCP_set_GCPX( GDAL_GCP *gcp, double dfGCPX ) { +void GDAL_GCP_GCPX_set( GDAL_GCP *gcp, double dfGCPX ) { gcp->dfGCPX = dfGCPX; } -double GDAL_GCP_get_GCPY( GDAL_GCP *gcp ) { +double GDAL_GCP_GCPY_get( GDAL_GCP *gcp ) { return gcp->dfGCPY; } -void GDAL_GCP_set_GCPY( GDAL_GCP *gcp, double dfGCPY ) { +void GDAL_GCP_GCPY_set( GDAL_GCP *gcp, double dfGCPY ) { gcp->dfGCPY = dfGCPY; } -double GDAL_GCP_get_GCPZ( GDAL_GCP *gcp ) { +double GDAL_GCP_GCPZ_get( GDAL_GCP *gcp ) { return gcp->dfGCPZ; } -void GDAL_GCP_set_GCPZ( GDAL_GCP *gcp, double dfGCPZ ) { +void GDAL_GCP_GCPZ_set( GDAL_GCP *gcp, double dfGCPZ ) { gcp->dfGCPZ = dfGCPZ; } -double GDAL_GCP_get_GCPPixel( GDAL_GCP *gcp ) { +double GDAL_GCP_GCPPixel_get( GDAL_GCP *gcp ) { return gcp->dfGCPPixel; } -void GDAL_GCP_set_GCPPixel( GDAL_GCP *gcp, double dfGCPPixel ) { +void GDAL_GCP_GCPPixel_set( GDAL_GCP *gcp, double dfGCPPixel ) { gcp->dfGCPPixel = dfGCPPixel; } -double GDAL_GCP_get_GCPLine( GDAL_GCP *gcp ) { +double GDAL_GCP_GCPLine_get( GDAL_GCP *gcp ) { return gcp->dfGCPLine; } -void GDAL_GCP_set_GCPLine( GDAL_GCP *gcp, double dfGCPLine ) { +void GDAL_GCP_GCPLine_set( GDAL_GCP *gcp, double dfGCPLine ) { gcp->dfGCPLine = dfGCPLine; } -const char * GDAL_GCP_get_Info( GDAL_GCP *gcp ) { +const char * GDAL_GCP_Info_get( GDAL_GCP *gcp ) { return gcp->pszInfo; } -void GDAL_GCP_set_Info( GDAL_GCP *gcp, const char * pszInfo ) { +void GDAL_GCP_Info_set( GDAL_GCP *gcp, const char * pszInfo ) { if ( gcp->pszInfo ) CPLFree( gcp->pszInfo ); gcp->pszInfo = CPLStrdup(pszInfo); } -const char * GDAL_GCP_get_Id( GDAL_GCP *gcp ) { +const char * GDAL_GCP_Id_get( GDAL_GCP *gcp ) { return gcp->pszId; } -void GDAL_GCP_set_Id( GDAL_GCP *gcp, const char * pszId ) { +void GDAL_GCP_Id_set( GDAL_GCP *gcp, const char * pszId ) { if ( gcp->pszId ) CPLFree( gcp->pszId ); gcp->pszId = CPLStrdup(pszId); } -%} //%inline -#endif //if defined(SWIGCSHARP) +%} +#endif %clear GDAL_GCP *gcp; -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (GCPsToGeoTransform) wrapper_GDALGCPsToGeoTransform; %inline { @@ -615,7 +617,7 @@ RETURN_NONE GDALGCPsToGeoTransform( int nGCPs, GDAL_GCP const * pGCPs, %clear (RETURN_NONE); #endif -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (GCPsToHomography) wrapper_GDALGCPsToHomography; %inline { @@ -733,18 +735,22 @@ RETURN_NONE GDALInvHomography( double h_in[9], double h_out[9] ); %clear (double *h_in); %clear (double *h_out); +#ifdef SWIGPYTHON +const char *GDALVersionInfo( const char *request = "VERSION_NUM" ); +#else +%rename (VersionInfo) wrapper_GDALVersionInfo; #ifdef SWIGJAVA %apply (const char* stringWithDefaultValue) {const char *request}; -%rename (VersionInfo) wrapper_GDALVersionInfo; +#endif %inline { const char *wrapper_GDALVersionInfo( const char *request = "VERSION_NUM" ) { return GDALVersionInfo(request ? request : "VERSION_NUM"); } } +#ifdef SWIGJAVA %clear (const char* request); -#else -const char *GDALVersionInfo( const char *request = "VERSION_NUM" ); +#endif #endif void GDALAllRegister(); @@ -825,9 +831,13 @@ GDALColorInterp GDALGetColorInterpretationByName( const char* pszColorInterpName const char *GDALGetPaletteInterpretationName( GDALPaletteInterp ePaletteInterp ); +#ifdef SWIGPYTHON +const char *GDALDecToDMS( double, const char *, int nPrecision = 2 ); +#else +%rename (DecToDMS) wrapper_GDALDecToDMS; #ifdef SWIGJAVA %apply (const char* stringWithDefaultValue) {const char *request}; -%rename (DecToDMS) wrapper_GDALDecToDMS; +#endif %inline { const char *wrapper_GDALDecToDMS( double dfAngle, const char * pszAxis, int nPrecision = 2 ) @@ -835,9 +845,9 @@ const char *wrapper_GDALDecToDMS( double dfAngle, const char * pszAxis, return GDALDecToDMS(dfAngle, pszAxis, nPrecision); } } +#ifdef SWIGJAVA %clear (const char* request); -#else -const char *GDALDecToDMS( double, const char *, int = 2 ); +#endif #endif double GDALPackedDMSToDec( double dfPacked ); @@ -949,6 +959,17 @@ GDALDatasetShadow* Open( char const* path, GDALAccess eAccess = GA_ReadOnly ) { #endif +#if defined(SWIGCSHARP) +%csmethodmodifiers wrapper_GetOpenDatasets "private"; +%apply (int *object_list_count, GDALDatasetShadow **poObjects) {(int *datasets, GDALDatasetShadow **pDatasets)}; +%inline %{ + void wrapper_GetOpenDatasets(int *datasets, GDALDatasetShadow **pDatasets ){ + GDALGetOpenDatasets((GDALDatasetH**)pDatasets, datasets); + } +%} +%clear (int *datasets, GDALDatasetShadow **pDatasets); +#endif + %newobject OpenEx; #ifdef SWIGPYTHON %rename (Open) OpenEx; @@ -1332,7 +1353,7 @@ struct GDALTranslateOptions { #ifdef SWIGPYTHON %rename (TranslateInternal) wrapper_GDALTranslate; -#elif defined(SWIGJAVA) +#elif defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (Translate) wrapper_GDALTranslate; #endif %newobject wrapper_GDALTranslate; @@ -1394,7 +1415,7 @@ struct GDALWarpAppOptions { } }; -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (Warp) wrapper_GDALWarpDestDS; #endif @@ -1442,7 +1463,7 @@ int wrapper_GDALWarpDestDS( GDALDatasetShadow* dstDS, %} %clear GDALDatasetShadow* dstDS; -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (Warp) wrapper_GDALWarpDestName; #endif @@ -1507,7 +1528,7 @@ struct GDALVectorTranslateOptions { /* Note: we must use 2 distinct names due to different ownership of the result */ -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (VectorTranslate) wrapper_GDALVectorTranslateDestDS; #endif @@ -1549,7 +1570,7 @@ int wrapper_GDALVectorTranslateDestDS( GDALDatasetShadow* dstDS, } %} -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (VectorTranslate) wrapper_GDALVectorTranslateDestName; #endif %newobject wrapper_GDALVectorTranslateDestName; @@ -1613,7 +1634,7 @@ struct GDALDEMProcessingOptions { #ifdef SWIGPYTHON %rename (DEMProcessingInternal) wrapper_GDALDEMProcessing; -#elif defined(SWIGJAVA) +#elif defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (DEMProcessing) wrapper_GDALDEMProcessing; #endif %newobject wrapper_GDALDEMProcessing; @@ -1680,7 +1701,7 @@ struct GDALNearblackOptions { /* Note: we must use 2 distinct names due to different ownership of the result */ -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (Nearblack) wrapper_GDALNearblackDestDS; #endif %inline %{ @@ -1721,7 +1742,7 @@ int wrapper_GDALNearblackDestDS( GDALDatasetShadow* dstDS, } %} -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (Nearblack) wrapper_GDALNearblackDestName; #endif %newobject wrapper_GDALNearblackDestName; @@ -1785,7 +1806,7 @@ struct GDALGridOptions { #ifdef SWIGPYTHON %rename (GridInternal) wrapper_GDALGrid; -#elif defined(SWIGJAVA) +#elif defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (Grid) wrapper_GDALGrid; #endif %newobject wrapper_GDALGrid; @@ -1850,7 +1871,7 @@ struct GDALContourOptions { /* Note: we must use 2 distinct names due to different ownership of the result */ -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (Contour) wrapper_GDALContourDestDS; #endif %inline %{ @@ -1898,7 +1919,7 @@ int wrapper_GDALContourDestDS( GDALDatasetShadow* dstDS, } %} -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (Contour) wrapper_GDALContourDestName; #endif %newobject wrapper_GDALContourDestName; @@ -1976,7 +1997,7 @@ struct GDALRasterizeOptions { /* Note: we must use 2 distinct names due to different ownership of the result */ -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (Rasterize) wrapper_GDALRasterizeDestDS; #endif %inline %{ @@ -2017,7 +2038,7 @@ int wrapper_GDALRasterizeDestDS( GDALDatasetShadow* dstDS, } %} -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (Rasterize) wrapper_GDALRasterizeDestName; #endif %newobject wrapper_GDALRasterizeDestName; @@ -2081,7 +2102,7 @@ struct GDALFootprintOptions { /* Note: we must use 2 distinct names due to different ownership of the result */ -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (Footprint) wrapper_GDALFootprintDestDS; #endif %inline %{ @@ -2122,7 +2143,7 @@ int wrapper_GDALFootprintDestDS( GDALDatasetShadow* dstDS, } %} -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (Footprint) wrapper_GDALFootprintDestName; #endif %newobject wrapper_GDALFootprintDestName; @@ -2186,7 +2207,7 @@ struct GDALBuildVRTOptions { #ifdef SWIGPYTHON %rename (BuildVRTInternalObjects) wrapper_GDALBuildVRT_objects; -#elif defined(SWIGJAVA) +#else %rename (BuildVRT) wrapper_GDALBuildVRT_objects; #endif @@ -2233,7 +2254,7 @@ GDALDatasetShadow* wrapper_GDALBuildVRT_objects( const char* dest, #ifdef SWIGPYTHON %rename (BuildVRTInternalNames) wrapper_GDALBuildVRT_names; -#elif defined(SWIGJAVA) +#else %rename (BuildVRT) wrapper_GDALBuildVRT_names; #endif @@ -2299,7 +2320,7 @@ struct GDALTileIndexOptions { #ifdef SWIGPYTHON %rename (TileIndexInternalNames) wrapper_TileIndex_names; -#elif defined(SWIGJAVA) +#elif defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (TileIndex) wrapper_TileIndex_names; #endif %newobject wrapper_TileIndex_names; @@ -2368,7 +2389,7 @@ struct GDALMultiDimTranslateOptions { } }; -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) %rename (MultiDimTranslate) wrapper_GDALMultiDimTranslateDestName; #endif diff --git a/swig/include/gnm.i b/swig/include/gnm.i index a5eb970efefe..decf5e49836c 100644 --- a/swig/include/gnm.i +++ b/swig/include/gnm.i @@ -29,7 +29,7 @@ %include swig_csharp_extensions.i #endif -#ifndef SWIGJAVA +#if !defined(SWIGJAVA) && !defined(SWIGCSHARP) %feature ("compactdefaultargs"); #endif diff --git a/swig/include/ogr.i b/swig/include/ogr.i index 13b61fe4fcee..a295fb6a99d2 100644 --- a/swig/include/ogr.i +++ b/swig/include/ogr.i @@ -45,7 +45,7 @@ typedef const char StringAsByteArray; %include swig_csharp_extensions.i #endif -#ifndef SWIGJAVA +#if !defined(SWIGJAVA) && !defined(SWIGCSHARP) %feature("compactdefaultargs"); #endif @@ -1334,15 +1334,9 @@ public: return (OGRGeometryShadow *) OGR_L_GetSpatialFilter(self); } -#ifdef SWIGCSHARP - %apply ( const char *utf8_string ) { (char* filter_string) }; -#endif OGRErr SetAttributeFilter(char* filter_string) { return OGR_L_SetAttributeFilter((OGRLayerShadow*)self, filter_string); } -#ifdef SWIGCSHARP - %clear (char* filter_string); -#endif const char * GetAttributeFilter() { return OGR_L_GetAttributeFilter(self); @@ -1413,13 +1407,8 @@ public: return OGR_L_UpsertFeature(self, feature); } -#if defined(SWIGCSHARP) -%apply int PINNED[] {int *panUpdatedFieldsIdx}; -%apply int PINNED[] {int *panUpdatedGeomFieldsIdx}; -#else %apply (int nList, int *pList ) { (int nUpdatedFieldsCount, int *panUpdatedFieldsIdx ) }; %apply (int nList, int *pList ) { (int nUpdatedGeomFieldsCount, int *panUpdatedGeomFieldsIdx ) }; -#endif OGRErr UpdateFeature(OGRFeatureShadow *feature, int nUpdatedFieldsCount, const int *panUpdatedFieldsIdx, @@ -1433,13 +1422,8 @@ public: panUpdatedGeomFieldsIdx, bUpdateStyleString); } -#if defined(SWIGCSHARP) -%clear int *panUpdatedFieldsIdx; -%clear int *panUpdatedGeomFieldsIdx; -#else %clear (int nUpdatedFieldsCount, int *panUpdatedFieldsIdx ); %clear (int nUpdatedGeomFieldsCount, int *panUpdatedGeomFieldsIdx ); -#endif %clear OGRFeatureShadow *feature; OGRErr DeleteFeature(GIntBig fid) { @@ -1466,10 +1450,15 @@ public: } #if defined(SWIGCSHARP) - %feature( "kwargs" ) GetExtent; OGRErr GetExtent(OGREnvelope* extent, int force=1) { return OGR_L_GetExtent(self, extent, force); } + bool GetExtent(int geom_field, OGREnvelope* extent, bool force=TRUE) { + return OGR_L_GetExtentEx(self, geom_field, extent, force) == OGRERR_NONE; + } + bool GetExtent3D(int geom_field, OGREnvelope3D* extent, bool force=TRUE) { + return OGR_L_GetExtent3D(self, geom_field, extent, force) == OGRERR_NONE; + } #elif defined(SWIGPYTHON) %feature( "kwargs" ) GetExtent; void GetExtent(double argout[4], int* isvalid = NULL, int force = 1, int can_return_null = 0, int geom_field = 0 ) { @@ -2188,6 +2177,15 @@ public: const int *GetFieldAsIntegerList(int id, int *count) { return OGR_F_GetFieldAsIntegerList(self, id, count); } + const int *GetFieldAsIntegerList(const char* field_name, int *count) { + int id = OGR_F_GetFieldIndex(self, field_name); + if (id == -1) { + CPLError(CE_Failure, 1, FIELD_NAME_ERROR_TMPL, field_name); + return NULL; + } + else + return OGR_F_GetFieldAsIntegerList(self, id, count); + } %clear (const int *); %clear (int *count); #else @@ -2208,6 +2206,23 @@ public: void GetFieldAsInteger64List(int id, int *nLen, const GIntBig **pList) { *pList = OGR_F_GetFieldAsInteger64List(self, id, nLen); } +#elif defined(SWIGCSHARP) + %apply (GIntBig *longList) {const GIntBig *}; + %apply (int *hasval) {int *count}; + const GIntBig *GetFieldAsInteger64List(int id, int *count) { + return OGR_F_GetFieldAsInteger64List(self, id, count); + } + const GIntBig *GetFieldAsInteger64List(const char* field_name, int *count) { + int id = OGR_F_GetFieldIndex(self, field_name); + if (id == -1) { + CPLError(CE_Failure, 1, FIELD_NAME_ERROR_TMPL, field_name); + return NULL; + } + else + return OGR_F_GetFieldAsInteger64List(self, id, count); + } + %clear (const GIntBig *); + %clear (int *count); #endif #if defined(SWIGJAVA) @@ -2221,6 +2236,15 @@ public: const double *GetFieldAsDoubleList(int id, int *count) { return OGR_F_GetFieldAsDoubleList(self, id, count); } + const double *GetFieldAsDoubleList(const char* field_name, int *count) { + int id = OGR_F_GetFieldIndex(self, field_name); + if (id == -1) { + CPLError(CE_Failure, 1, FIELD_NAME_ERROR_TMPL, field_name); + return NULL; + } + else + return OGR_F_GetFieldAsDoubleList(self, id, count); + } %clear (const double *); %clear (int *count); #else @@ -2248,6 +2272,16 @@ public: char **GetFieldAsStringList(int id) { return OGR_F_GetFieldAsStringList(self, id); } + + char **GetFieldAsStringList(const char* field_name) { + int id = OGR_F_GetFieldIndex(self, field_name); + if (id == -1) { + CPLError(CE_Failure, 1, FIELD_NAME_ERROR_TMPL, field_name); + return NULL; + } + else + return OGR_F_GetFieldAsStringList(self, id); + } %clear (char **); #else void GetFieldAsStringList(int id, char ***pList) { @@ -2263,7 +2297,6 @@ public: } #endif -#ifndef SWIGCSHARP #ifdef SWIGJAVA %apply (GByte* outBytes) {GByte*}; GByte* GetFieldAsBinary(int id, int *nLen, char **pBuf) { @@ -2289,7 +2322,7 @@ public: } } %clear GByte*; -#else +#elif defined(SWIGPYTHON) OGRErr GetFieldAsBinary( int id, int *nLen, char **pBuf) { GByte* pabyBlob = OGR_F_GetFieldAsBinary(self, id, nLen); *pBuf = (char*)VSIMalloc(*nLen); @@ -2312,8 +2345,23 @@ public: return OGRERR_NONE; } } -#endif /* SWIGJAVA */ - +#else /* SWIGPYTHON */ + %apply (GByte *byteList) {const GByte *}; + %apply (int *hasval) {int *count}; + const GByte *GetFieldAsBinary(int id, int *count) { + return OGR_F_GetFieldAsBinary(self, id, count); + } + const GByte *GetFieldAsBinary(const char* field_name, int *count) { + int id = OGR_F_GetFieldIndex(self, field_name); + if (id == -1) { + CPLError(CE_Failure, 1, FIELD_NAME_ERROR_TMPL, field_name); + return NULL; + } + else + return OGR_F_GetFieldAsBinary(self, id, count); + } + %clear (const GByte *); + %clear (int *count); #endif /* SWIGCSHARP */ /* ---- IsFieldSet --------------------------- */ @@ -2415,11 +2463,7 @@ public: } /* ---- SetField ----------------------------- */ -#ifndef SWIGCSHARP - %apply ( tostring argin ) { (const char* value) }; -#else %apply ( const char *utf8_string ) { (const char* value) }; -#endif void SetField(int id, const char* value) { OGR_F_SetFieldString(self, id, value); } @@ -2488,7 +2532,7 @@ public: OGR_F_SetFieldIntegerList(self, id, nList, pList); } -#if defined(SWIGPYTHON) +#if defined(SWIGPYTHON) || defined(SWIGCSHARP) void SetFieldInteger64List(int id, int nList, GIntBig *pList) { OGR_F_SetFieldInteger64List(self, id, nList, pList); } @@ -2503,12 +2547,64 @@ public: void SetFieldStringList(int id, char **pList) { OGR_F_SetFieldStringList(self, id, pList); } + +#if defined(SWIGCSHARP) + void SetFieldInteger64(const char* field_name, GIntBig value) { + int id = OGR_F_GetFieldIndex(self, field_name); + if (id == -1) + CPLError(CE_Failure, 1, FIELD_NAME_ERROR_TMPL, field_name); + else + OGR_F_SetFieldInteger64(self, id, value); + } + void SetFieldStringList(const char* field_name, char **pList) { + int id = OGR_F_GetFieldIndex(self, field_name); + if (id == -1) + CPLError(CE_Failure, 1, FIELD_NAME_ERROR_TMPL, field_name); + else + OGR_F_SetFieldStringList(self, id, pList); + } + void SetFieldIntegerList(const char* field_name, int nList, int *pList) { + int id = OGR_F_GetFieldIndex(self, field_name); + if (id == -1) + CPLError(CE_Failure, 1, FIELD_NAME_ERROR_TMPL, field_name); + else + OGR_F_SetFieldIntegerList(self, id, nList, pList); + } + void SetFieldInteger64List(const char* field_name, int nList, GIntBig *pList) { + int id = OGR_F_GetFieldIndex(self, field_name); + if (id == -1) + CPLError(CE_Failure, 1, FIELD_NAME_ERROR_TMPL, field_name); + else + OGR_F_SetFieldInteger64List(self, id, nList, pList); + } + void SetFieldDoubleList(const char* field_name, int nList, double *pList) { + int id = OGR_F_GetFieldIndex(self, field_name); + if (id == -1) + CPLError(CE_Failure, 1, FIELD_NAME_ERROR_TMPL, field_name); + else + OGR_F_SetFieldDoubleList(self, id, nList, pList); + } +#endif + %clear char**pList; #if defined(SWIGPYTHON) void _SetFieldBinary(int id, int nLen, char *pBuf) { OGR_F_SetFieldBinary(self, id, nLen, pBuf); } +#elif defined(SWIGCSHARP) + %apply (int nList, char *pList) {(int bytes, char *pBuf)}; + void SetFieldBinary(int id, int bytes, char *pBuf) { + OGR_F_SetFieldBinary(self, id, bytes, pBuf); + } + void SetFieldBinary(const char* field_name, int bytes, char *pBuf) { + int id = OGR_F_GetFieldIndex(self, field_name); + if (id == -1) + CPLError(CE_Failure, 1, FIELD_NAME_ERROR_TMPL, field_name); + else + OGR_F_SetFieldBinary(self, id, bytes, pBuf); + } + %clear (int bytes, char *pBuf); #endif void SetFieldBinaryFromHexString(int id, const char* pszValue) @@ -2890,9 +2986,6 @@ public: #ifndef SWIGJAVA %feature("kwargs") OGRFieldDefnShadow; -#endif -#ifdef SWIGCSHARP - %apply ( const char *utf8_string ) { (const char* name_null_ok) }; #endif OGRFieldDefnShadow( const char* name_null_ok="unnamed", OGRFieldType field_type=OFTString) { @@ -2901,19 +2994,10 @@ public: else return NULL; } -#ifdef SWIGCSHARP - %clear (const char* name_null_ok ); -#endif -#ifdef SWIGCSHARP - %apply ( const char *utf8_string ) { const char * GetName }; -#endif const char * GetName() { return OGR_Fld_GetNameRef(self); } -#ifdef SWIGCSHARP - %clear (const char * GetName ); -#endif #ifdef SWIGJAVA StringAsByteArray* GetNameAsByteArray() { @@ -2925,18 +3009,10 @@ public: return OGR_Fld_GetNameRef(self); } -#ifdef SWIGCSHARP - %apply ( const char *utf8_string ) { (const char* name) }; -#endif - void SetName( const char* name) { OGR_Fld_SetName(self, name); } -#ifdef SWIGCSHARP - %clear (const char* name ); -#endif - const char * GetAlternativeName() { return OGR_Fld_GetAlternativeNameRef(self); } @@ -3211,7 +3287,8 @@ public: #ifndef SWIGCSHARP %apply (size_t nLen, char *pBuf ) { (size_t len, char *bin_string)}; #else -%apply (void *buffer_ptr) {char *bin_string}; +%apply (size_t native_size) {(size_t len)}; +%apply (void *buffer_ptr) {(char * bin_string)}; #endif %inline %{ OGRGeometryShadow* CreateGeometryFromWkb( size_t len, char *bin_string, @@ -3229,11 +3306,11 @@ public: } %} -#endif #ifndef SWIGCSHARP %clear (size_t len, char *bin_string); #else -%clear (char *bin_string); +%clear (size_t len), (char * bin_string); +#endif #endif #ifdef SWIGJAVA @@ -3301,7 +3378,6 @@ OGRGeometryShadow* CreateGeometryFromWkb(int nLen, unsigned char *pBuf, %} -#ifndef SWIGCSHARP %newobject CreateGeometryFromEnvelope; %inline %{ OGRGeometryShadow *CreateGeometryFromEnvelope(double xmin, @@ -3313,7 +3389,6 @@ OGRGeometryShadow* CreateGeometryFromWkb(int nLen, unsigned char *pBuf, return geom; } %} -#endif %newobject BuildPolygonFromEdges; #ifndef SWIGJAVA @@ -3429,6 +3504,8 @@ OGRGeometryShadow* ForceTo( OGRGeometryShadow *geom_in, OGRwkbGeometryType eTarg /* OGRGeometry */ /************************************************************************/ +/* ignore overload which splits multi-argument typemap*/ +%ignore OGRGeometryShadow::OGRGeometryShadow(OGRwkbGeometryType,char *,int wkb); %rename (Geometry) OGRGeometryShadow; class OGRGeometryShadow { OGRGeometryShadow(); @@ -3441,7 +3518,7 @@ public: #ifndef SWIGJAVA #ifdef SWIGCSHARP -%apply (void *buffer_ptr) {char *wkb_buf}; +%apply (int nList, char *pList) {(int wkb, char *wkb_buf)}; #else %apply (int nLen, char *pBuf) {(int wkb, char *wkb_buf)}; #endif @@ -3453,7 +3530,7 @@ public: else if ( wkt != 0 ) { return CreateGeometryFromWkt( &wkt ); } - else if ( wkb != 0 ) { + else if ( wkb != 0 && wkb_buf) { return CreateGeometryFromWkb( wkb, wkb_buf ); } else if ( gml != 0 ) { @@ -3465,12 +3542,8 @@ public: return NULL;} } -#ifdef SWIGCSHARP -%clear (char *wkb_buf); -#else %clear (int wkb, char *wkb_buf); -#endif -#endif +#endif //SWIGJAVA OGRErr ExportToWkt( char** argout ) { return OGR_G_ExportToWkt(self, argout); @@ -3769,7 +3842,7 @@ public: return OGR_G_GetM(self, point); } -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) void GetPoint(int iPoint, double argout[3]) { #else void GetPoint(int iPoint = 0, double argout[3] = NULL) { @@ -3777,7 +3850,7 @@ public: OGR_G_GetPoint( self, iPoint, argout+0, argout+1, argout+2 ); } -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) void GetPointZM(int iPoint, double argout[4]) { #else void GetPointZM(int iPoint = 0, double argout[4] = NULL) { @@ -3785,7 +3858,7 @@ public: OGR_G_GetPointZM( self, iPoint, argout+0, argout+1, argout+2, argout+3 ); } -#ifdef SWIGJAVA +#if defined(SWIGJAVA) || defined(SWIGCSHARP) void GetPoint_2D(int iPoint, double argout[2]) { #else void GetPoint_2D(int iPoint = 0, double argout[2] = NULL) { @@ -3793,6 +3866,20 @@ public: OGR_G_GetPoint( self, iPoint, argout+0, argout+1, NULL ); } +#if defined(SWIGCSHARP) +%apply (double *OUTPUT) {double *x, double *y, double *z, double *m}; + void GetPoint(int iPoint, double *x, double *y) { + OGR_G_GetPoint( self, iPoint, x, y, NULL ); + } + void GetPoint(int iPoint, double *x, double *y, double *z) { + OGR_G_GetPoint( self, iPoint, x, y, z ); + } + void GetPoint(int iPoint, double *x, double *y, double *z, double *m) { + OGR_G_GetPointZM( self, iPoint, x, y, z, m ); + } +%clear double *x, double *y, double *z, double *m; +#endif + int GetGeometryCount() { return OGR_G_GetGeometryCount(self); } @@ -4314,11 +4401,9 @@ public: OGR_FldDomain_SetMergePolicy(self, policy); } -#if defined(SWIGPYTHON) || defined(SWIGJAVA) const OGRCodedValue* GetEnumeration() { return OGR_CodedFldDomain_GetEnumeration(self); } -#endif double GetMinAsDouble() { const OGRField* psVal = OGR_RangeFldDomain_GetMin(self, NULL); @@ -4418,7 +4503,6 @@ public: }; /* class OGRFieldDomainShadow */ -#if defined(SWIGPYTHON) || defined(SWIGJAVA) %newobject CreateCodedFieldDomain; %apply Pointer NONNULL {const char* name}; %inline %{ @@ -4436,7 +4520,6 @@ OGRFieldDomainShadow* CreateCodedFieldDomain( const char *name, } %} %clear const char* name; -#endif %newobject CreateRangeFieldDomain; %apply Pointer NONNULL {const char* name}; @@ -4764,7 +4847,7 @@ int OGRGetNonLinearGeometriesEnabledFlag(void); } %} -#if !(defined(FROM_GDAL_I) && (defined(SWIGJAVA) || defined(SWIGPYTHON))) +#if !(defined(FROM_GDAL_I) && (defined(SWIGJAVA) || defined(SWIGPYTHON) || defined(SWIGCSHARP))) #ifdef SWIGPYTHON %thread; @@ -4804,11 +4887,9 @@ int OGRGetNonLinearGeometriesEnabledFlag(void); #ifdef SWIGPYTHON %thread; -#endif -%newobject OpenShared; -#ifndef SWIGJAVA %feature( "kwargs" ) OpenShared; #endif +%newobject OpenShared; %inline %{ OGRDataSourceShadow* OpenShared( const char *utf8_string, int update =0 ) { CPLErrorReset(); @@ -4835,7 +4916,7 @@ int OGRGetNonLinearGeometriesEnabledFlag(void); %nothread; #endif -#endif /* !(defined(FROM_GDAL_I) && (defined(SWIGJAVA) || defined(SWIGPYTHON))) */ +#endif /* !(defined(FROM_GDAL_I) && (defined(SWIGJAVA) || defined(SWIGPYTHON) || defined(SWIGCSHARP))) */ #ifndef FROM_GDAL_I diff --git a/swig/include/osr.i b/swig/include/osr.i index 7ab0e21f90e5..f62779faa06f 100644 --- a/swig/include/osr.i +++ b/swig/include/osr.i @@ -28,7 +28,7 @@ %include swig_csharp_extensions.i #endif -#ifndef SWIGJAVA +#if !defined(SWIGJAVA) && !defined(SWIGCSHARP) %feature("compactdefaultargs"); #endif @@ -567,12 +567,13 @@ public: { *matches = OSRFindMatches(self, options, nvalues, confidence_values); } +%clear (int *nvalues, CTYPE **confidence_values); #endif #ifdef SWIGCSHARP - OSRSpatialReferenceShadow** FindMatches(char** options, int* nvalues, int** confidence_values) + OSRSpatialReferenceShadow** FindMatches(char** options, int* confidence_values, int** ppanMatchConfidence ) { - return (OSRSpatialReferenceShadow**) OSRFindMatches(self, options, nvalues, confidence_values); + return (OSRSpatialReferenceShadow**) OSRFindMatches(self, options, confidence_values, ppanMatchConfidence); } #endif @@ -1376,21 +1377,40 @@ public: } #endif -#ifdef SWIGCSHARP - %apply (double *inout) {(double*)}; -#endif - -#ifndef SWIGPYTHON - void TransformPoints( int nCount, double *x, double *y, double *z ) { +#ifdef SWIGPYTHON + void TransformPoints( int nCount, double *x, double *y, double *z, double *t ) { if (self == NULL) return; - OCTTransform( self, nCount, x, y, z ); + OCTTransform4D( self, nCount, x, y, z, t, NULL ); } +#elif defined(SWIGCSHARP) +/* ignore overload which splits multi-argument typemap*/ +%ignore TransformPoints(int,double *,int,double *,int); +%ignore TransformPoints(int,double *,int,double *,int,double *,int); +%ignore TransformPoints(int,double *,int,double *,int,double *,int,double *,int); +%apply (int nList, double *pList) { (int x, double *pX), (int y, double *pY), (int z, double *pZ), (int t, double *pT) }; +%apply (int nList, int *pList) { (int success, int *panSuccess) }; + bool TransformPoints( int x, double *pX, int y, double *pY, + int z = 0, double *pZ = NULL, int t = 0, double *pT = NULL, + int success = 0, int *panSuccess = NULL) { + CPLErrorReset(); + if (!pX || !pY) { + CPLError(CE_Failure, CPLE_IllegalArg, "All x and y arrays must be non-null."); + return 0; + } + else if (x != y || (pZ && x != z) || (pT && x != t) || (panSuccess && x != success)) { + CPLError(CE_Failure, CPLE_IllegalArg, "All arrays must be the same size."); + return 0; + } + return OCTTransform4D( self, x, pX, pY, pZ, pT, panSuccess ); + } +%clear (int x, double *pX), (int y, double *pY), (int z, double *pZ), (int t, double *pT); +%clear (int success, int *panSuccess); #else - void TransformPoints( int nCount, double *x, double *y, double *z, double *t ) { + void TransformPoints( int nCount, double *x, double *y, double *z ) { if (self == NULL) return; - OCTTransform4D( self, nCount, x, y, z, t, NULL ); + OCTTransform( self, nCount, x, y, z ); } #endif @@ -1407,10 +1427,29 @@ public: return NULL; } %clear int*; -#endif - -#ifdef SWIGCSHARP - %clear (double*); +#elif defined(SWIGCSHARP) +/* ignore overload which splits multi-argument typemap*/ +%ignore TransformPointsWithErrorCodes(int,double *,int,double *,int); +%ignore TransformPointsWithErrorCodes(int,double *,int,double *,int,double *,int); +%ignore TransformPointsWithErrorCodes(int,double *,int,double *,int,double *,int,double *,int); +%apply (int nList, double *pList) { (int x, double *pX), (int y, double *pY), (int z, double *pZ), (int t, double *pT) }; +%apply (int nList, int *pList) { (int errorCodes, int *panErrorCodes) }; + bool TransformPointsWithErrorCodes( int x, double *pX, int y, double *pY, + int z = 0, double *pZ = NULL, int t = 0, double *pT = NULL, + int errorCodes = 0, int *panErrorCodes = NULL) { + CPLErrorReset(); + if (!pX || !pY) { + CPLError(CE_Failure, CPLE_IllegalArg, "All x and y arrays must be non-null."); + return 0; + } + else if (x != y || (pZ && x != z) || (pT && x != t) || (panErrorCodes && x != errorCodes)) { + CPLError(CE_Failure, CPLE_IllegalArg, "All arrays must be the same size."); + return 0; + } + return OCTTransform4DWithErrorCodes( self, x, pX, pY, pZ, pT, panErrorCodes ); + } +%clear (int x, double *pX), (int y, double *pY), (int z, double *pZ), (int t, double *pT); +%clear (int errorCodes, int *panErrorCodes); #endif void TransformBounds(