C# 在IronPython中如何读取公共固定字节?

C# 在IronPython中如何读取公共固定字节?,c#,python,ironpython,C#,Python,Ironpython,在C#中,我有一个属性声明为: public fixed byte foo[10] 在客户端代码中,我看到它使用此函数转换为字符串: public static unsafe string GetString(byte* byteArray) { return new String((sbyte*)byteArray); } 在IronPython打印中,它将类型作为字符串提供给我: >>> print obj.foo Baz+<foo>e__FixedBu

在C#中,我有一个属性声明为:

public fixed byte foo[10]
在客户端代码中,我看到它使用此函数转换为字符串:

public static unsafe string GetString(byte* byteArray)
{
  return new String((sbyte*)byteArray);
}
在IronPython打印中,它将类型作为字符串提供给我:

>>> print obj.foo
Baz+<foo>e__FixedBuffer1
>>打印obj.foo
Baz+e__固定缓冲区1
尝试使用转换函数时出错

>>> print GetString(obj.foo)
expected Byte*, got <Foo>e__FixedBuffer1
打印GetString(obj.foo) 应为字节*,已获得e_uuFixedBuffer1
在IronPython中读取此属性的正确方法是什么?

在.NET中,固定字段非常特殊。您拥有的固定字段(
public fixed byte foo[10]
)被编译成一个特殊的嵌套结构,并且您的固定字段的类型被更改为该嵌套结构。简言之,这是:

public fixed byte foo[10];
编译成以下格式:

// This is the struct that was generated, it contains a field with the
// first element of your fixed array
[CompilerGenerated, UnsafeValueType]
[StructLayout(LayoutKind.Sequential, Size = 10)]
public struct <foo>e__FixedBuffer0
{
    public byte FixedElementField;
}

// This is your original field with the new type
[FixedBuffer(typeof(byte), 10)]
public <foo>e__FixedBuffer0 foo;
因此,它从字面上获取数组第一个元素的地址,并将其作为参数传递给方法(因此,
GetString
参数的类型正确,
byte*

在IronPython中使用相同的参数调用相同的方法时,参数类型仍然是字段的类型:
e\uu FixedBuffer0
,不能转换为
byte*
(显然)。进行此方法调用的正确方法是执行与C#编译器相同的替换-获取
FixedElementField
的地址并将其传递给
GetString
,但不幸的是,Python(据我所知)没有类似于C#中的
&
运算符

结论是:您不能直接从IronPython访问固定字段。我想说,您最好的选择是使用“代理”方法,如:

public string GetFooString(Baz baz)
{
    return new string((sbyte*)baz.foo);
}

PS我不是IronPython专业人士,因此可能有一种超级方法可以直接访问foo道具,但我不知道如何使用。

什么是cchar?我找不到它应该是什么的参考资料。或者你是说char?cchar是byte,他忘了使用cchar=System.byte;在这个问题上。用公共固定字节foo[10]替换他的公共固定字节foo[10]我将问题改为使用
byte
。如果在
返回中看到不匹配的参数,可能需要将其清除以避免混淆。
public string GetFooString(Baz baz)
{
    return new string((sbyte*)baz.foo);
}