首页 > 解决方案 > Detect specific return type of C# function python.net

问题描述

Let's say I have the following C# function

public byte AddOne(byte r){

    return r + 1
}

In my python code, I am able to call the function by doing something like

x = AddOne(3)

When I check the type of x, it always returns an int. This is true even if I change my C# function to return a long, a short, or an int. I want x to be a numpy.int8 if a byte is returned, or numpy.int64 if long is returned. How can I go about doing this since currently an int is always returned?

标签: pythonc#python-3.xpython.net

解决方案


在 Python.NET 2.5+ 中,您可以定义自定义编解码器。在 2.5 中,它们不能用于覆盖原始类型转换,但是,在 C# 端,您可以定义与 、 等对应的自定义类型numpy.int64numpy.int8然后为它们注册编解码器。

public struct I8 {
  public byte Value;

  static I8() {
    var i8 = Py.Import("numpy").GetAttr("int8");
    PyObjectConversions.RegisterEncoder(new I8Codec(i8));
  }
}

public class I8Codec: IPyObjectEncoder {
  readonly PyObject i8;
  public I8Codec(PyObject i8) => this.i8 = i8;

  public PyObject TryEncode(object value)
    // call numpy.int8 constructor
    => i8.Invoke(((I8)value).Value.ToPython());

  public PyObject CanEncode(Type type) => type == typeof(I8);
}

I8 DoubleIt(byte val) => new I8 { Value = val*2 };

或者,您可以修改此行以允许原始类型的编解码器,并实现I8Codecfor byte. 但是,尝试这样做int可能会导致意想不到的后果。例如ICollection.Count将开始返回numpy.int32,您可能不想要。


推荐阅读