python - 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?
解决方案
在 Python.NET 2.5+ 中,您可以定义自定义编解码器。在 2.5 中,它们不能用于覆盖原始类型转换,但是,在 C# 端,您可以定义与 、 等对应的自定义类型numpy.int64
,numpy.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 };
或者,您可以修改此行以允许原始类型的编解码器,并实现I8Codec
for byte
. 但是,尝试这样做int
可能会导致意想不到的后果。例如ICollection.Count
将开始返回numpy.int32
,您可能不想要。
推荐阅读
- visual-studio-code - 即使在关闭编辑器后如何保持编辑器组固定?
- c - 在 c 中释放 2d 矩阵时正确使用 free()
- java - Vaadin DateField 具有空值和占位符
- asp.net-mvc - 带有子查询列表的 LINQ 查询
- java - Spring Framework 未映射到我的控制器
- arrays - 如何将数据存储在 Angular 5 本地存储中
- firefox - Firefox - “阻止所有 Cookie”不起作用
- node.js - Angular CLI UnhandledPromiseRejectionWarning 全新安装
- node.js - 谷歌云存储节点客户端 ResumableUploadError
- php - Regex match any url's in string with and without www and create a clickable URL