回答編集履歴

1

BSTR に変更

2022/05/30 19:34

投稿

KOZ6.0
KOZ6.0

スコア2626

test CHANGED
@@ -5,35 +5,41 @@
5
5
 
6
6
  class Program
7
7
  {
8
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
8
+ [StructLayout(LayoutKind.Sequential)]
9
9
  public struct Test
10
10
  {
11
- [MarshalAs(UnmanagedType.LPStr)]
11
+ [MarshalAs(UnmanagedType.BStr)]
12
12
  public string x;
13
- [MarshalAs(UnmanagedType.LPStr)]
13
+ [MarshalAs(UnmanagedType.BStr)]
14
14
  public string y;
15
- [MarshalAs(UnmanagedType.LPStr)]
15
+ [MarshalAs(UnmanagedType.BStr)]
16
16
  public string z;
17
17
  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
18
18
  public test1[] test1s;
19
19
  }
20
20
 
21
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
21
+ [StructLayout(LayoutKind.Sequential)]
22
22
  public struct test1
23
23
  {
24
- [MarshalAs(UnmanagedType.LPStr)]
24
+ [MarshalAs(UnmanagedType.BStr)]
25
25
  public string e;
26
26
  }
27
27
 
28
28
  static void Main(string[] args) {
29
+ // BSTR 文字列のアドレスを格納する配列を作成
29
30
  IntPtr[] input = new IntPtr[5];
30
31
  for (int i = 0; i < input.Length; i++) {
31
- input[i] = Marshal.StringToCoTaskMemAuto((i + 1).ToString());
32
+ input[i] = Marshal.StringToBSTR((i + 1).ToString());
32
33
  }
34
+ // 配列を Test 構造体にコピー
33
35
  GCHandle gch = GCHandle.Alloc(input, GCHandleType.Pinned);
34
36
  Test result = (Test)Marshal.PtrToStructure(gch.AddrOfPinnedObject(), typeof(Test));
35
37
  gch.Free();
36
-
38
+ // 不要になった BSTR 文字列を解放
39
+ for (int i = 0; i < input.Length; i++) {
40
+ Marshal.FreeBSTR(input[i]);
41
+ }
42
+ // 結果確認
37
43
  Console.WriteLine(result.x);
38
44
  Console.WriteLine(result.y);
39
45
  Console.WriteLine(result.z);
@@ -41,9 +47,6 @@
41
47
  Console.WriteLine(result.test1s[1].e);
42
48
  Console.ReadKey();
43
49
 
44
- for (int i = 0; i < input.Length; i++) {
45
- Marshal.FreeCoTaskMem(input[i]);
46
- }
47
50
  }
48
51
  }
49
52
  ```