解决 GDAL 用 C# 访问时,中文乱码问题。

下面代码用于获取中文图层名、字段名及字段值。

public class SafeOgr
{
    /// <summary>
    /// 获取图层名(自动处理 UTF-8 编码)
    /// </summary>
    [DllImport("gdal.dll", EntryPoint = "OGR_L_GetName", CallingConvention = CallingConvention.Cdecl)]
    static extern IntPtr OGR_L_GetName(HandleRef handle);
    public static string GetLayerName(Layer layer)
    {
        HandleRef handle = Layer.getCPtr(layer);
        IntPtr ptr = OGR_L_GetName(handle);
        return Utf8BytesToString(ptr);
    }

    /// <summary>
    /// 获取字段名(自动处理 UTF-8 编码)
    /// </summary>
    [DllImport("gdal.dll", EntryPoint = "OGR_Fld_GetNameRef", CallingConvention = CallingConvention.Cdecl)]
    static extern IntPtr OGR_Fld_GetNameRef(HandleRef handle);
    public static string GetFieldName(FieldDefn field)
    {
        HandleRef handle = FieldDefn.getCPtr(field);
        IntPtr ptr = OGR_Fld_GetNameRef(handle);
        return Utf8BytesToString(ptr);
    }

    /// <summary>
    /// 获取字段值字符串(自动处理 UTF-8 编码)
    /// </summary>
    [DllImport("gdal.dll", EntryPoint = "OGR_F_GetFieldAsString", CallingConvention = CallingConvention.Cdecl)]
    static extern IntPtr OGR_F_GetFieldAsString(HandleRef handle, int idx);
    public static string GetFieldAsString(Feature feat, int idx)
    {
        HandleRef handle = Feature.getCPtr(feat);
        IntPtr ptr = OGR_F_GetFieldAsString(handle, idx);
        return Utf8BytesToString(ptr);
    }

    private static string Utf8BytesToString(IntPtr ptr)
    {
        if (ptr == IntPtr.Zero)
            return null;

        int len = 0;
        while (Marshal.ReadByte(ptr, len) != 0) len++;

        byte[] bytes = new byte[len];
        Marshal.Copy(ptr, bytes, 0, len);

        return System.Text.Encoding.UTF8.GetString(bytes);
    }
}

 

posted @ 2026-04-28 20:21  神游虚空  阅读(1)  评论(0)    收藏  举报