我正在制作一个c#程序来绘制用c计算的三次样条曲线,这是程序的互操作部分
我的c#代码:
[DllImport(@"..\..\..\Debug\Spline_Core.dll")]
static extern IntPtr mult_points(Point[] points, int points_count, double factor);
public Form1()
{
InitializeComponent();
var points = new[]
{
new Point { x = 2, y = 3 },
new Point { x = 5, y = 7 },
};
var sum = mult_points(points, 2, 2);
var mult = (Point[])Marshal.PtrToStructure(sum, typeof(Point[]));
}
和c代码:
typedef struct point
{
double x, y;
} Point;
extern __declspec(dllexport) Point* __stdcall mult_points(Point* points, int points_count, double factor)
{
int i;
Point* mult_points = (Point*)malloc(points_count * sizeof(Point));
for (i = 0; i < points_count; i++)
mult_points[i] = create_point(points[i].x * factor, points[i].y * factor);
return mult_points;
}
我可以通过c#到c的参数传递点数组,但是我无法将其取回。
答案 0 :(得分:-1)
Point*
只是指向单个Point
结构的指针。编组器不知道它是一个数组还是这个数组中有多少个元素。所以你的演员Point[]
是错误的。
为了更好地理解,请参阅此简单示例 - 而不是此代码:
var sum = mult_points(points, 2, 2);
var mult = (Point[])Marshal.PtrToStructure(sum, typeof(Point[]));
......你可以使用这样的东西:
IntPtr sum = mult_points(points, 2, 2);
int structSize = Marshal.SizeOf(typeof(Point));
for (int i = 0; i < numberOfPoints; i++)
{
IntPtr curr = sum + (i * structSize);
Point pt = (Point)Marshal.PtrToStructure(curr, typeof(Point));
// Add pt to List<Point> for example
}
这不是一个理想的解决方案,但我希望你明白这一点。 可以在此处找到更好(更优雅)的解决方案:How do I marshall a pointer to a pointer of an array of structures?