1 Star 0 Fork 11

tianhett/FinanceSdkDemo

forked from Yohao丶/FinanceSdkDemo 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
UTF8Marshaler.cs 1.78 KB
一键复制 编辑 原始数据 按行查看 历史
Yohao.Chou 提交于 2020-09-26 23:53 . init demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace FinanceSdkDemo
{
//接口数据为utf-8编码所设置
public class UTF8Marshaler : ICustomMarshaler
{
public void CleanUpManagedData(object managedObj)
{
}
public void CleanUpNativeData(IntPtr pNativeData)
{
Marshal.FreeHGlobal(pNativeData);
}
public int GetNativeDataSize()
{
return -1;
}
public IntPtr MarshalManagedToNative(object managedObj)
{
if (object.ReferenceEquals(managedObj, null))
return IntPtr.Zero;
if (!(managedObj is string))
throw new InvalidOperationException();
byte[] utf8bytes = Encoding.UTF8.GetBytes(managedObj as string);
IntPtr ptr = Marshal.AllocHGlobal(utf8bytes.Length + 1);
Marshal.Copy(utf8bytes, 0, ptr, utf8bytes.Length);
Marshal.WriteByte(ptr, utf8bytes.Length, 0);
return ptr;
}
public object MarshalNativeToManaged(IntPtr pNativeData)
{
if (pNativeData == IntPtr.Zero)
return null;
List<byte> bytes = new List<byte>();
for (int offset = 0; ; offset++)
{
byte b = Marshal.ReadByte(pNativeData, offset);
if (b == 0) break;
else bytes.Add(b);
}
return Encoding.UTF8.GetString(bytes.ToArray(), 0, bytes.Count);
}
private static UTF8Marshaler instance = new UTF8Marshaler();
public static ICustomMarshaler GetInstance(string cookie)
{
return instance;
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/tianhett/finance-sdk-demo.git
git@gitee.com:tianhett/finance-sdk-demo.git
tianhett
finance-sdk-demo
FinanceSdkDemo
master

搜索帮助