■ Marshal 클래스의 Copy 정적 메소드를 사용해 문자열을 fixed char 필드에 복사하는 방법을 보여준다.
▶ Student.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
using System; namespace TestProject { /// <summary> /// 학생 /// </summary> public unsafe struct Student { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// ID /// </summary> public int ID; /// <summary> /// 성명 /// </summary> public fixed char Name[20]; /// <summary> /// 생성 시간 /// </summary> public DateTime CreateTime; #endregion } } |
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
using System; using System.Runtime.InteropServices; namespace TestProject { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 복사하기 - Copy(source, target) /// <summary> /// 복사하기 /// </summary> /// <param name="source">소스 문자열</param> /// <param name="target">타겟 포인터</param> private unsafe static void Copy(string source, char* target) { char[] sourceCharArray = source.ToCharArray(); Marshal.Copy(sourceCharArray, 0, new IntPtr(target), sourceCharArray.Length); } #endregion #region 문자열 구하기 - GetString(sourcePointer) /// <summary> /// 문자열 구하기 /// </summary> /// <param name="sourcePointer">소스 포인터</param> /// <returns>문자열</returns> private unsafe static string GetString(char* sourcePointer) { return new string(sourcePointer); } #endregion #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private unsafe static void Main() { Student student = new Student(); Copy("홍길동", student.Name); string name = GetString(student.Name); Console.WriteLine(name); } #endregion } } |