Cで作成したDLLに、構造体へのポインタをメンバに含む構造体のポインタのポインタを引数として渡す方法を試してみた。
DLL側のソース
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#pragma once #define Dll_Test_CPP_API __declspec(dllexport) typedef struct { double x; char y; } childT; typedef struct { int xx; childT* yy; } topT; extern "C" Dll_Test_CPP_API void testStruct(int a, double b, char c, topT** d); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include "pch.h" #include <stdio.h> #include <stdlib.h> #include "Dll_Test_CPP.h" void testStruct(int a, double b, char c, topT** d) { topT* tT; childT* ct; tT = *d; ct = tT->yy; tT->xx = a; ct->x = b; ct->y = c; } |
C#側
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 |
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 IntPtr 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 ptT = new IntPtr(); IntPtr lst_p = Marshal.AllocHGlobal(Marshal.SizeOf(new childT())); tT.yy = lst_p; ptT = Marshal.AllocHGlobal(Marshal.SizeOf(ptT)); Marshal.StructureToPtr(tT, ptT, false); testStruct(10, 3.14, 'z', out ptT); var res1 = (topT)Marshal.PtrToStructure(ptT, typeof(topT)); var res2 = (childT)Marshal.PtrToStructure(res1.yy, typeof(childT)); textBox1.Text = textBox1.Text + "tT.xx = "+res1.xx.ToString() + "\r\ncT.x = " + res2.x.ToString() + "\r\ncT.y = " + res2.y.ToString() + "\r\n"; Marshal.FreeHGlobal(lst_p); Marshal.FreeHGlobal(ptT); } } } |
一応できたけど、これが正解なのかイマイチよくわからない。 SDRPlayのAPIはもっと複雑なので、このやりかたの延長でうまくいくのか不明。