Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

C#: in and ref parameters misinterpreted as out parameters#2630

Unanswered
nikitagrgv asked this question inQ&A
Discussion options

Hi, I'm trying to use pythonnet with a large C# codebase to expose it to python. I'm running into issues with methods that takein parameters.

Methods that takein orref parameters return tuples, as if they wereout parameters. Overloaded operators that usein parameters cause exceptions.

Here's a minimal repro:

usingPython.Runtime;namespacetestpy;publicclassMyClass(floatvalue){privatefloat_value=value;publicstaticMyClassoperator+(inMyClassv0,inMyClassv1){returnnewMyClass(v0._value+v1._value);}publicMyClassMyFunc(inMyClassother){returnnewMyClass(_value+other._value);}}classProgram{staticvoidMain(string[]args){Runtime.PythonDLL="python311.dll";PythonEngine.Initialize();using(Py.GIL()){dynamicpy=Py.CreateScope();py.Set("m1",newMyClass(1).ToPython());py.Set("m2",newMyClass(2).ToPython());stringcode=@"v1 = m1.MyFunc(m2)print(v1) # prints (<testpy.MyClass object at 0x00000000068FB780>, <testpy.MyClass object at 0x00000000068FB7C0>)v2 = m1 + m2 # exception";py.Exec(code);}}}

MyFunc returns a tuple containing the original return value and its argument.
m1 + m2 causes the following exception:

Python.Runtime.PythonException: <bound method 'op_Addition'> returned a result with an exception set ---> Python.Runtime.PythonException: tuple assignment index out of range   --- End of inner exception stack trace ---  File "<string>", line 4, in <module>   at Python.Runtime.PythonException.ThrowLastAsClrException()   at Python.Runtime.PythonException.ThrowIfIsNull(NewReference& ob)   at Python.Runtime.PyModule.Exec(String code, BorrowedReference _globals, BorrowedReference _locals)   at Python.Runtime.PyModule.Exec(String code, PyDict locals)   at CallSite.Target(Closure, CallSite, Object, String)   at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite site, T0 arg0, T1 arg1)   at testpy.Program.Main(String[] args) in C:\Users\User\RiderProjects\testpy\testpy\Program.cs:line 39

As I understand it, this happens becausein andout are C# features rather than dotnet, so pythonnet doesn’t care about it. But what can I do to fix this without rewriting any existing code?

NOTE: I see in debug thatthis code doesn't care aboutin, becausebinding.outs includesin parameters.

You must be logged in to vote

Replies: 0 comments

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Q&A
Labels
None yet
1 participant
@nikitagrgv

[8]ページ先頭

©2009-2025 Movatter.jp