2010-06-25 46 views
1

给定该结构在C#的结构:复制一个字符串转换为固定长度字节的缓冲区中

[StructLayout(LayoutKind.Sequential)] 
unsafe public struct AppVPEntry 
{ 
    public int Num; 
    public fixed byte CompName[256]; 
    public int VPBeginAddress; 
} 

请告诉我复制的字符串的最简单的方式(“C:\路径\ file.txt的”)到固定长度的缓冲区'CompName'。这是在一个结构被发送到一个古老的DLL,我们别无选择,只能使用。理想情况下,我喜欢使用.NET函数,但由于它是固定的,意味着“不安全”,我知道我在这里受到限制。一个更通用的函数会有帮助,因为我们已经在DLL导入空间中得到了像这样的字符串。

+0

你期望什么编码的字节? – 2010-06-25 16:23:37

回答

1
// 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); 
} 

您可能想检查字符串的大小是否不大于缓冲区的大小。

+0

我已经试过这个,它不起作用。这将返回一个托管字节结构,而结构定义中的'fixed'和'unsafe'意味着不受管理。不管怎么说,还是要谢谢你... – Gio 2010-06-25 16:24:49

0

试试看。在您可能传递VPEntry的任何地方,在您的DllImport中使用IntPtr。在你调用DLL方法的地方传递“非托管”字段。

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); 
    } 
} 
相关问题