C++动态库声明
在函数内修改数组内容,注意导出函数定义(extern "C"
)
#pragma pack(1)
struct Point
{
float x;
float y;
};
#pragma pack()
extern "C" __declspec(dllexport)
void __stdcall Test(Point *pt, int size)
{
for (int i = 0; i < size; ++i)
{
pt[i].x = (float)i;
pt[i].y = (float)2 * i;
}
}
C#导入DLL函数
注意[Out]
参数
using System;
using System.Runtime.InteropServices;
namespace ConsoleApp1
{
class Program
{
[StructLayout(LayoutKind.Sequential, Pack =1)]
public struct Point
{
public float x;
public float y;
}
[DllImport("Dll1.dll", EntryPoint ="Test", CallingConvention = CallingConvention.StdCall)]
public static extern void test([Out] [MarshalAs(UnmanagedType.LPArray, SizeConst = 5)] Point[] pts, int cnt);
static void Main(string[] args)
{
Point[] pts = new Point[5];
test(pts, 5);
for (int i = 0; i < pts.Length; ++i)
{
Console.WriteLine($"x={pts[i].x} y={pts[i].y}");
}
Console.ReadLine();
}
}
}