GADL/OGR C# 读取Dxf数据时,Feature的Layer属性中文乱码问题的解决

       最近,用GDAL/OGR,在.net环境中用C#读取Dxf数据时,在读取Feature的Layer属性时,总是出现乱码问题。设置了全局属性 OSGeo.GDAL.Gdal.SetConfigOption(“DXF_ENCODING”, “UTF-8”);问题依然存在。查看了C#下Ogr类的源码,转换函数如下:

internal static string Utf8BytesToString(IntPtr pNativeData)
  {
    if (pNativeData == IntPtr.Zero)
        return null;

    int length = Marshal.PtrToStringAnsi(pNativeData).Length;
    byte[] strbuf = new byte[length];
    Marshal.Copy(pNativeData, strbuf, 0, length); 
    return System.Text.Encoding.UTF8.GetString(strbuf);
   
  }

发现在读取中文时length的长度总是取错,因为UTF-8存储字节是不定长的,把函数修改为:

internal static string Utf8BytesToString(IntPtr pNativeData)
  {
    if (pNativeData == IntPtr.Zero)
        return null;

    int size = 0;
    byte[] buffer = {};
    do
    {
        ++size;
        Array.Resize(ref buffer, size);
        Marshal.Copy(pNativeData, buffer, 0, size);
    } while (buffer[size – 1] != 0); // till 0 termination found

    if (1 == size)
    {
        return “”; // empty string
    }

    Array.Resize(ref buffer, size – 1); // remove terminating 0
    return System.Text.Encoding.UTF8.GetString(buffer);
  }

重新编译后运行,中文乱码问题解决。

转载自:https://blog.csdn.net/gdsxsc/article/details/39452171

You may also like...