You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
86 lines
2.3 KiB
C#
86 lines
2.3 KiB
C#
using System;
|
|
using System.CodeDom;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Runtime.InteropServices;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace GeoSigmaDrawLib
|
|
{
|
|
/// <summary>
|
|
/// 表示一个按指定编码转换后的非托管内存文本缓冲区。
|
|
/// 支持自动释放,避免内存泄漏。
|
|
/// </summary>
|
|
public class NativeTextBuffer : IDisposable
|
|
{
|
|
private const string GB2312 = "GB2312";
|
|
|
|
/// <summary>
|
|
/// 编码类型枚举,便于调用方选择
|
|
/// </summary>
|
|
public enum EncodingType
|
|
{
|
|
GBK,
|
|
UTF8,
|
|
UTF16,
|
|
}
|
|
|
|
/// <summary>
|
|
/// 非托管内存指针
|
|
/// </summary>
|
|
public IntPtr Pointer { get; private set; }
|
|
|
|
/// <summary>
|
|
/// 缓冲区字节长度
|
|
/// </summary>
|
|
public int Length { get; private set; }
|
|
|
|
/// <summary>
|
|
/// 构造函数:根据指定编码将字符串转换为非托管内存缓冲区
|
|
/// </summary>
|
|
/// <param name="text">源文本</param>
|
|
/// <param name="encoding">目标编码</param>
|
|
public NativeTextBuffer(string text, EncodingType encoding = EncodingType.GBK)
|
|
{
|
|
if (text == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(text));
|
|
}
|
|
|
|
Encoding enc = Encoding.GetEncoding(GB2312);
|
|
|
|
switch (encoding)
|
|
{
|
|
case EncodingType.GBK:
|
|
enc = Encoding.GetEncoding(GB2312);
|
|
break;
|
|
case EncodingType.UTF8:
|
|
enc = Encoding.UTF8;
|
|
break;
|
|
case EncodingType.UTF16:
|
|
enc = Encoding.Unicode;
|
|
break;
|
|
}
|
|
|
|
byte[] bytes = enc.GetBytes(text);
|
|
|
|
Pointer = Marshal.AllocHGlobal(bytes.Length);
|
|
Marshal.Copy(bytes, 0, Pointer, bytes.Length);
|
|
Length = bytes.Length;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 释放非托管内存
|
|
/// </summary>
|
|
public void Dispose()
|
|
{
|
|
if (Pointer != IntPtr.Zero)
|
|
{
|
|
Marshal.FreeHGlobal(Pointer);
|
|
Pointer = IntPtr.Zero;
|
|
}
|
|
}
|
|
}
|
|
}
|