1
votes

My application uses IronPython for users to run scripts. One such script is used for setting the members of a structure. My Structure is as follows:

[StructLayout(LayoutKind.Sequential)]
public struct Data
{
    int a;
    int b;
}

I have declared a class level public object for this structure like:

public Data data = new data();

I am setting the data object as the scope variable for IronPython:

scope.SetVariable("data", data);

In the python script, I am setting the variables a and b:

data.a = 5
data.b = 10

But the variables are not changing in the C# code. I have noticed that if I use a normal integer or any other type, those variables are setting.

Is there some issue with using structures? How can I set the C# structure members from IronPython?

1
It is a valuetype, so you would need to return data and update it in C#. It seems you really just want a class instead of a struct. - leppie
@leppie: The structure is used to set similar structure members in unmanaged C++. It would be very tedious to create a class with the same members as the structure, pass it to IronPython and get the values then set the structure members from the class. - Abhishek
Fair point, the only easy solution I see here, is to re-assign data value after you done in IronPython, but this 'workflow' might not be desirable. - leppie
@leppie: Can you explain? - Abhishek
I have created a class with same members as the structure and passing it to IronPython. Then I am filling the structure with the values set through IronPython. I am using this as a temporary workaround. - Abhishek

1 Answers

0
votes

Use your exposed scope object to provide helper methods to scripts.
When I can't do it in IronPython that is what I do. IronPython gives me the flexibility of a full language with ifs, fors, and whiles but sometimes the answers for integrating with the C# world are fuzzy so I just build a helper method.

You can even type the parameters because the marshalling works well across function calls. void SetResult(int a, int b);

The minor comments are probably right you probably are setting the struct but the struct is not a pass by reference it is a pass by value.

You should understand this concept. Here is a good SO article about it ....
What's the difference between passing by reference vs. passing by value?

You can google the concept more yourself.