struct指针和固定char

时间:2015-01-27 14:09:29

标签: c# c++ dll struct unmarshalling

我的C ++中有一个像这样的结构

struct ST_HDTextInfo
{
    char* font_name;                    
    char* text;                          
    unsigned int font_color;             
    unsigned int background_color;      
    int style;                          
    int font_size;                       
    struct ST_HDTextInfo* next;        
};

我在我的C#代码中重新声明它

[StructLayout(LayoutKind.Sequential,Pack=4)]
    unsafe struct  ST_HDTextInfo
    {
        [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 25)]
        public fixed char font_name[25];
        [MarshalAs(UnmanagedType.ByValTStr, ArraySubType = UnmanagedType.I1, SizeConst = 20)]
        public char[] text;
        [MarshalAs(UnmanagedType.SysUInt)]
        public uint font_color;
        [MarshalAs(UnmanagedType.SysUInt)]
        public uint background_color;
        [MarshalAs(UnmanagedType.SysInt)]
        public EN_FontStyle style;
        [MarshalAs(UnmanagedType.SysInt)]
        public int font_size;
        [MarshalAs(UnmanagedType.SysInt)]
        public ST_HDTextInfo* next;
    };

字段 next 是指向相同结构的指针。当我使用 char [] var 作为字符串变量时,因为结构没有修复大小VS在公共ST_HDTextInfo * 下一步 时出错 但是当使用fixed char var [SIZE_OF_VAR]时问题解决但又出现了另一个错误。填充char *变量是一个新问题!我使用此代码将counrt字符串转换为char *

IntPtr p = Marshal.StringToHGlobalAuto("Poor Richard");
char* newCharStr = (char*)(p.ToPointer());

text_info.font_name = newCharStr; 

在这个站中我的字符串转换为char *但是VS接受此错误"作业的左侧必须是变量,属性或索引器" !!!

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。我使用这个示例代码

[StructLayoutAttribute(LayoutKind.Explicit, CharSet = CharSet.Auto, Size=80)]
    internal unsafe struct ST_HDTextInfo
    {
        [FieldOffset(0)]
        public fixed char text[25];
        [FieldOffset(0)]
        public fixed char font_name[20];
        [MarshalAs(UnmanagedType.I4)]
        [FieldOffset(0)]
        public uint font_color;
        [MarshalAs(UnmanagedType.I4)]
        [FieldOffset(0)]
        public uint background_color;
        [MarshalAs(UnmanagedType.I4)]
        [FieldOffset(0)]
        public EN_FontStyle style;
        [MarshalAs(UnmanagedType.I4)]
        [FieldOffset(0)]
        public int font_size;
        [FieldOffset(80 - sizeof(long))]
        public ST_HDTextInfo* next;
    };