gpt4 book ai didi

c# - 使用 StructureToPtr 将 C# 结构编码为 C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:30:40 24 4
gpt4 key购买 nike

我有 C# 类:

namespace Models
{
[StructLayout(LayoutKind.Explicit, Size = 120, CharSet = CharSet.Unicode)]
public struct DynamicState
{
[FieldOffset(0)]
public double[] Position;

[FieldOffset(24)]
public double[] Velocity;

[FieldOffset(48)]
public double[] Acceleration;

[FieldOffset(72)]
public double[] Attitude;

[FieldOffset(96)]
public double[] AngularVelocity;
}
}

和 C++/CLI 方法:

Models::DynamicState SomeClassClr::DoSomething(Models::DynamicState ds)
{
int struct_size = Marshal::SizeOf(ds);
System::IntPtr ptr = Marshal::AllocHGlobal(struct_size);
DynamicStateStruct ds_struct;
struct_size = sizeof(ds_struct);

Marshal::StructureToPtr(ds, ptr, false);
ds_struct = *(DynamicStateStruct*)ptr.ToPointer();

Models::DynamicState returnVal;
mpSomeClass->doSomething(ds_struct);

return returnVal;
}

其中 DynamicStateStruct 是原生 C++ 类:

struct DynamicStateStruct
{
double mPosition[3];
double mVelocity[3];
double mAcceleration[3];
double mAttitude[3];
double mAngularVelocity[3];
};

当我在 native C++ 中恢复结构 (ds_struct) 时,我没有得到正确的值,对我缺少的有什么想法吗?

最佳答案

尝试以下变体:

public struct DynamicState
{
[MarshalAs (UnmanagedType.ByValArray, SizeConst=3)]
public double[] Position;

[MarshalAs (UnmanagedType.ByValArray, SizeConst=3)]
public double[] Velocity;

[MarshalAs (UnmanagedType.ByValArray, SizeConst=3)]
public double[] Acceleration;

[MarshalAs (UnmanagedType.ByValArray, SizeConst=3)]
public double[] Attitude;

[MarshalAs (UnmanagedType.ByValArray, SizeConst=3)]
public double[] AngularVelocity;
}

另一种选择是使用不安全代码中可用的固定数组:

public unsafe struct DynamicState
{
public fixed double Position[3];

public fixed double Velocity[3];

public fixed double Acceleration[3];

public fixed double Attitude[3];

public fixed double AngularVelocity[3];
}

附言可以在此处找到有关 .Net 互操作的良好指南:http://www.mono-project.com/Interop_with_Native_Libraries

关于c# - 使用 StructureToPtr 将 C# 结构编码为 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12747330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com