1

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?

Abhishek
  • 2,925
  • 4
  • 34
  • 59
  • 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 Jan 19 '15 at 07:43
  • @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 Jan 19 '15 at 07:52
  • 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 Jan 19 '15 at 07:55
  • @leppie: Can you explain? – Abhishek Jan 20 '15 at 00:53
  • 1
    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 Jan 21 '15 at 00:09
  • That is probably better than I suggested :) – leppie Jan 21 '15 at 04:34

1 Answers1

0

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.

Community
  • 1
  • 1
cbuteau
  • 736
  • 1
  • 7
  • 15