C# 将字符串复制到结构中的固定长度字节缓冲区
鉴于c#中的这种结构: 将字符串(“c:\path\file.txt”)复制到固定长度缓冲区“CompName”的最简单方法是什么。这是一个结构,它被发送到一个古老的DLL,我们别无选择,只能使用它。理想情况下,我希望使用.NET函数,但由于它是固定的,这意味着“不安全”,我知道我在这里受到限制。一个更通用的函数会有所帮助,因为我们在DLL导入空间中都有这样的字符串C# 将字符串复制到结构中的固定长度字节缓冲区,c#,string,dll,C#,String,Dll,鉴于c#中的这种结构: 将字符串(“c:\path\file.txt”)复制到固定长度缓冲区“CompName”的最简单方法是什么。这是一个结构,它被发送到一个古老的DLL,我们别无选择,只能使用它。理想情况下,我希望使用.NET函数,但由于它是固定的,这意味着“不安全”,我知道我在这里受到限制。一个更通用的函数会有所帮助,因为我们在DLL导入空间中都有这样的字符串 // C# to convert a string to a byte array. public static byte[] S
// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}
您可能需要检查字符串的大小是否小于缓冲区的大小
您可能需要检查字符串的大小是否小于缓冲区的大小。试试这个。无论您在哪里传递VPEntry,都可以在DllImport中使用IntPtr。在调用DLL方法的任何位置传递“unmanaged”字段
public sealed class AppVPEntry : IDisposable {
[StructLayout(LayoutKind.Sequential, Size = 264)]
internal struct _AppVPEntry {
[MarshalAs(UnmanagedType.I4)]
public Int32 Num;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
public Byte[] CompName;
[MarshalAs(UnmanagedType.I4)]
public Int32 VPBeginAddress;
}
private readonly IntPtr unmanaged;
private readonly _AppVPEntry managed = new _AppVPEntry();
public AppVPEntry(Int32 num, String path, Int32 beginAddress) {
this.managed.Num = num;
this.managed.CompName = new byte[256];
Buffer.BlockCopy(Encoding.ASCII.GetBytes(path), 0, this.managed.CompName, 0, Math.Min(path.Length, 256));
this.managed.VPBeginAddress = beginAddress;
this.unmanaged = Marshal.AllocHGlobal(264);
Marshal.StructureToPtr(this.managed, this.unmanaged, false);
}
public void Dispose() {
Marshal.FreeHGlobal(this.unmanaged);
}
}
试试这个。无论您在哪里传递VPEntry,都可以在DllImport中使用IntPtr。在调用DLL方法的任何位置传递“unmanaged”字段
public sealed class AppVPEntry : IDisposable {
[StructLayout(LayoutKind.Sequential, Size = 264)]
internal struct _AppVPEntry {
[MarshalAs(UnmanagedType.I4)]
public Int32 Num;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
public Byte[] CompName;
[MarshalAs(UnmanagedType.I4)]
public Int32 VPBeginAddress;
}
private readonly IntPtr unmanaged;
private readonly _AppVPEntry managed = new _AppVPEntry();
public AppVPEntry(Int32 num, String path, Int32 beginAddress) {
this.managed.Num = num;
this.managed.CompName = new byte[256];
Buffer.BlockCopy(Encoding.ASCII.GetBytes(path), 0, this.managed.CompName, 0, Math.Min(path.Length, 256));
this.managed.VPBeginAddress = beginAddress;
this.unmanaged = Marshal.AllocHGlobal(264);
Marshal.StructureToPtr(this.managed, this.unmanaged, false);
}
public void Dispose() {
Marshal.FreeHGlobal(this.unmanaged);
}
}
你希望字节采用什么编码?你希望字节采用什么编码?我已经试过了,但它不起作用。这将返回托管字节结构,而结构定义中的“固定”和“不安全”表示非托管。无论如何,谢谢你…我已经试过了,但它不起作用。这将返回托管字节结构,而结构定义中的“固定”和“不安全”表示非托管。无论如何谢谢你。。。