code
2020-08-08 19:12:44 于 杂谈
class Program
{
[StructLayout(LayoutKind.Sequential)]
struct ST
{
public int a;
public int b;
public int c;
};
[DllImport("../../Debug/cpp_dll1.dll", EntryPoint = "?Test@@YAXPAUST@@I@Z")]
unsafe extern static void Test(ST* datas, int count);
static void Main(string[] args)
{
Console.WriteLine(System.Environment.CurrentDirectory);
unsafe
{
int count = 128;
// 申请内存
var sz = Marshal.SizeOf(typeof(ST));
IntPtr ptr = IntPtr.Zero;
ptr = Marshal.AllocHGlobal(count * sz);
// 指针转类型
Test((ST*)ptr, count);
for (int i = 0; i < count; ++i)
{
var data = *((ST*)ptr + i);
Console.WriteLine("{0}, {1}, {2}", data.a, data.b, data.c);
}
// 释放内存(必须要释放!)
Marshal.FreeHGlobal(ptr);
}
}
}
