我有一个C#应用程序,需要与Python共享一些二进制数据,我计划使用共享内存(内存映射文件).因此,我需要在两边有相同的二进制 struct .
我在C#(ST_Layer
)中创建了一个 struct ,它包含另一个 struct (ST_Point
)的项array.为了访问这些项目,我定义了一个函数getPoint
,它将返回指向被请求的ST_Point
的位置的指针.
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
class TestProgram
{
[StructLayout(LayoutKind.Explicit, Pack = 8)]
public struct ST_Point
{
[FieldOffset(0)] public double X;
[FieldOffset(8)] public double Y;
}
[StructLayout(LayoutKind.Explicit, Pack = 8)]
public unsafe struct ST_Layer
{
[FieldOffset(0)] public ushort nPoints;
[FieldOffset(8)] public double fHeight;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
[FieldOffset(16)] public ST_Point[] Points;
public unsafe ST_Point* getPoint(int n)
{
fixed (ST_Layer* thisPtr = &this)
{
int ptr = (int)&(thisPtr->Points) + n * ((16 + 3) / 4) * 4; // Sizeof ST_Point 16
return (ST_Point*)ptr;
}
}
}
static void Main(string[] args)
{
unsafe
{
ST_Layer layer = new ST_Layer();
layer.nPoints = 3;
layer.fHeight = 4;
layer.getPoint(0)->X = 5;
layer.getPoint(3)->Y = 6;
for (int i = 0; i < 10; i++)
Debug.WriteLine("Data [" + i + "] " + layer.getPoint(i)->X + ", " + layer.getPoint(i)->Y + " - ");
while (true)
Thread.Sleep(50);
}
}
}
我有两个问题:
- 如果我编译x86的代码,那么前面的代码就可以工作了,但x64或"Any CPU"("System. System.AdditionViolationException"exception in "layer. getPoint(0)—X")则不行.>这是一种预期的行为吗?如何解决此异常?
- 我使用
getPoint
函数来访问ST_Point
数组,因为我还没有看到更好的访问方法.是否可以将其作为普通数组(即layer.Points[0].X
)进行访问?我不能创建ST_Point
(layer.Points = new ST_Point[10]
)的数组,因为它将在ST_Layer
之外创建,并且数据不会传递给Python.
我见过this和this,但不知道如何访问ST_Point
的各个字段.
感谢你的帮助.
[Also谢谢R.Martinho Fernandes为你的hint regarding the x86/x64 issue]