Skip to content

Instantly share code, notes, and snippets.

@attentive
Created April 30, 2024 08:39
Show Gist options
  • Save attentive/33cc47a2d0d143e1e695131e1fcd19dc to your computer and use it in GitHub Desktop.
Save attentive/33cc47a2d0d143e1e695131e1fcd19dc to your computer and use it in GitHub Desktop.
Read the raw data from a GDAL VSI file in C#
/// <summary>
/// On various GDAL mailing lists and forums one can find people complaining about the lack of the VSIFReadL
/// function in GDAL's C# bindings, which allows data to be read from a GDAL "virtual file".
///
/// An example is here: https://lists.osgeo.org/pipermail/gdal-dev/2018-July/048838.html
///
/// However it is possible to use .NET Platform Invoke as below to call this function straight from the native
/// GDAL DLL entry point.
/// </summary>
internal static class GdalReadVsiFile
{
/// <summary>
/// This is needed because the GDAL SWIG bindings are missing the required read function.
/// </summary>
/// <param name="buffer">A data into which GDAL will read</param>
/// <param name="memberSize">Size of each member of the buffer (always 1 as we are going by bytes)</param>
/// <param name="memberCount">Count of members in the buffer</param>
/// <param name="vsiFile">Pointer to a GDAL VSIFile structure (opaque to this client code)</param>
/// <returns>(Presumably) the number of bytes read, but we don't care</returns>
[DllImport(
@"PATH_TO_GDAL_NATIVE_PACKAGE\gdal.dll",
CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Unicode,
SetLastError = true)]
internal static extern int VSIFReadL(
[MarshalAs(UnmanagedType.LPArray)] byte[] buffer,
[MarshalAs(UnmanagedType.U4)] uint memberSize,
[MarshalAs(UnmanagedType.U4)] uint memberCount,
IntPtr vsiFile);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment