【发布时间】:2012-04-13 13:09:25
【问题描述】:
我正在使用从非托管代码到托管 C# 代码的回调函数。回调有一个参数void* eventData。 EventData 可以是几种不同的结构类型。在我的 C# 代码中,我将 eventData 定义为 IntPtr 并使用 Marshal.PtrToStructure 来获取结构。对于大多数结构我没有问题。但是,我遇到了编组这个问题:
//! Structure for dose parameters
typedef struct
{
//! the dose in µGrays
float dose;
unsigned short nbParameters;
//! the corresponding parameters specified in the .ini file
struct Parameters
{
//! parameter text
const char* text;
//! parameter value
float value;
} * parameters;
} DoseParameters;
这是我对结构的 C# 定义:
/// <summary>
/// Structure for dose parameters
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct DoseParameters {
//! the dose in µGrays
public float dose;
public ushort nbParameters;
//! the corresponding parameters specified in the .ini file
[StructLayout(LayoutKind.Sequential)]
public struct Parameters{
//! parameter text
public string text;
//! parameter value
public float value;
}
[MarshalAs(UnmanagedType.ByValArray)]
public Parameters[] parameters;
}
dose 和 nbParameters 值已正确转换。这是我正在努力解决的参数数组。长度始终为 1,对于该实例,Parameters.text 是不可理解的,Parameters.value 远大于应有的值。
这似乎与 char * 的长度不确定有关。虽然,我是新来的 StructLayout/MarshalAs 的东西所以不太确定这一切。我玩过各种 MarshalAs、LayoutKind.Explicit 和 FieldOffset 组合,但没有成功(显然)。我已经进行了一些搜索,但没有找到与我的情况相似的任何东西。
【问题讨论】:
-
[MarshalAs(UnmanagedType.ByValArray)]肯定不正确——我怀疑应该是UnmanagedType.LPArray。
标签: c# c++ marshalling structlayout