我有这样的结构:
[StructLayout(LayoutKind.Sequential)]
internal struct EVENT_TRACE_PROPERTIES
{
internal WNODE_HEADER WNode;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)EventTracePropertiesStringSize)]
internal string LoggerName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)EventTracePropertiesStringSize)]
internal string LogFileName;
}
如何复制C#字符串,str为LogFileName指向的结构内存位置?
答案 0 :(得分:2)
您只需指定字段:
EVENT_TRACE_PROPERTIES item;
item.LogFileName = "My String";
答案 1 :(得分:0)
我使用以下内容来分配和检索值:
[TestFixture]
public class MarshalAsTest
{
[Test]
public void TestMarshalAs_SetLogFileName( )
{
SomeClass someClass = new SomeClass( );
string logFile = "LogFileName.log";
someClass.SetLogFile(logFile);
Assert.AreEqual(logFile, someClass.GetLogFile( ));
}
}
public class SomeClass
{
EVENT_TRACE_PROPERTIES props;
public void SetLogFile([MarshalAs(UnmanagedType.LPWStr)]String msg)
{
props.LogFileName = msg;
}
[return: MarshalAs(UnmanagedType.LPWStr)]
public string GetLogFile( )
{
return props.LogFileName;
}
[StructLayout(LayoutKind.Sequential)]
internal struct EVENT_TRACE_PROPERTIES
{
internal WNODE_HEADER WNode;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
internal string LoggerName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
internal string LogFileName;
}
}
注意:我使用了16的SizeConst作为任意值。