unsafe修飾子を使わない方法
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 |
using System; using System.Windows.Forms; using System.Runtime.InteropServices; namespace DllTestAPISharp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } [StructLayout(LayoutKind.Sequential)] public struct childT { public double x; public char y; } [StructLayout(LayoutKind.Sequential)] public unsafe struct topT { public int xx; public IntPtr yy; } [DllImport("Dll_Test_CPP.dll", CallingConvention = CallingConvention.Cdecl)] private extern static void testStruct(int a, double b, char c, out topT d); private void button1_Click(object sender, EventArgs e) { textBox1.Text = "void testStruct(int a, double b, char c, out topT d)\r\n"; topT tT = new topT(); IntPtr lst_p = Marshal.AllocCoTaskMem(Marshal.SizeOf(new childT())); tT.yy = lst_p; testStruct(10, 3.14, 'z', out tT); var res = (childT)Marshal.PtrToStructure(tT.yy, typeof(childT)); textBox1.Text = textBox1.Text + "tT.xx = "+tT.xx.ToString() + "\r\ncT.x = " + res.x.ToString() + "\r\ncT.y = " + res.y.ToString() + "\r\n"; Marshal.FreeCoTaskMem(lst_p); } } } |
Marshal.AllocCoTaskMem関数で、メモリを確保してtopTのIntPtr変数にポインタを渡しているので、やっていることは前とほぼ同じ。
素直にポインタを使ったほうが、すっきりする。