Python .net framework reference argument Double[]&

风流意气都作罢 提交于 2019-12-06 04:45:48

问题


Using the Python for .Net framework I'm trying to call a method from a C# .dll file. This method has the following arguments:

public static void ExternalFunction(
    String Arg1,
    ref Double[]& Arg2,
);

I understood the .Net framework converts Python floats to doubles. Now I would like to know how to make an array (double) and pass this as a reference to the external method.

I've the following code:

import clr

clr.AddReference("MyDll")
from MyLib import MyClass

myName = "Benjamin"

r = MyClass.ExternalFunction(myName, 0.0);
print "Result: %s"%r

回答1:


You can call this method by providing a list (or tuple) of floats as a second parameter.

MyClass.ExternalFunction(myName, [0.0]);

There will be a conversion between 2 different data structures in 2 virtual machines. Python.Net will convert python's list of floats to an array of doubles in .Net environment and pass it by reference to your function. Changes made to second parameter will not be propagated back to python.

By using reflection you can get more control over parameters marshaling.

import clr
clr.AddReference("MyDll")
import System
import MyLib

myClassType = System.Type.GetType("MyLib.MyClass, MyDll") 
method = myClassType.GetMethod("ExternalFunction")
numbersArray = System.Array[System.Double]([1.0, 2.0, 3.0])
parameters = System.Array[System.Object](["Benjamin",numbersArray])
method.Invoke(None,parameters)


numbersArray = parameters[1] # an updated Arg2 can be retrieved from parameters array


来源:https://stackoverflow.com/questions/16484167/python-net-framework-reference-argument-double

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