Creating a C# Nullable Int32 within Python (using Python.NET) to call a C# method with an optional int argument

£可爱£侵袭症+ 提交于 2019-12-29 07:52:43

问题


I'm using Python.NET to load a C# Assembly to call C# code from Python. This works pretty cleanly, however I am having an issue calling a method that looks like this:

A method within Our.Namespace.Proj.MyRepo:

OutputObject GetData(string user, int anID, int? anOptionalID= null)

I can call the method for the case where the optional third argument is present but can't figure out what to pass for the third argument to match the null case.

import clr
clr.AddReference("Our.Namespace.Proj")
import System
from Our.Namespace.Proj import MyRepo

_repo = MyRepo()

_repo.GetData('me', System.Int32(1), System.Int32(2))  # works!

_repo.GetData('me', System.Int32(1))  # fails! TypeError: No method matches given arguments

_repo.GetData('me', System.Int32(1), None)  # fails! TypeError: No method matches given arguments

The iPython Notebook indicates that the last argument should be of type:

System.Nullable`1[System.Int32]

Just not sure how to create an object that will match the Null case.

Any suggestions on how to create a C# recognized Null object? I assumed passing the native Python None would work, but it does not.


回答1:


[EDIT]

This has been merged to pythonnet:

https://github.com/pythonnet/pythonnet/pull/460


I ran into the same issue with nullable primitives -- it seems to me that Python.NET doesn't support these types. I got around the problem by adding the following code in Python.Runtime.Converter.ToManagedValue() (\src\runtime\converter.cs)

if( obType.IsGenericType && obType.GetGenericTypeDefinition() == typeof(Nullable<>) )
{
    if( value == Runtime.PyNone )
    {
        result = null;
        return true;
    }
    // Set type to underlying type
    obType = obType.GetGenericArguments()[0];
}

I placed this code right underneath

if (value == Runtime.PyNone && !obType.IsValueType) {
    result = null;
    return true;
}

https://github.com/pythonnet/pythonnet/blob/4df6105b98b302029e524c7ce36f7b3cb18f7040/src/runtime/converter.cs#L320




回答2:


I have no way to test this, but try

_repo.GetData('me', System.Int32(1), System.Nullable[System.Int32]())

Since you're saying that the optional parameter is Nullable, you need to create a new Nullable object of type Int32, or new System.Nullable<int>() in C# code.

I would have assumed that the first failing example would work, given that this is how optional parameters work in C#; calling the function without specifying the parameter at all.




回答3:


You have to pass argument to generic function System.Nullable[System.Int32](0)



来源:https://stackoverflow.com/questions/26742837/creating-a-c-sharp-nullable-int32-within-python-using-python-net-to-call-a-c-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!