0

I am starting with C++/CLI combined with IronPython :) I ran into problem with managed structures in Python code. My structure looks like this

[System::Runtime::InteropServices::StructLayout(
    System::Runtime::InteropServices::LayoutKind::Sequential)]
public value struct VersionInfo
{
    [System::Runtime::InteropServices::MarshalAsAttribute(
        System::Runtime::InteropServices::UnmanagedType::U4)]
    DWORD Major;
};

Passing this structure to Python is as follows

VersionInfo^ vi = gcnew VersionInfo();
vi->Major = 12345;

IronPython::Runtime::PythonFunction^ function = 
    (IronPython::Runtime::PythonFunction^)
        m_PluginScope->GetVariable("GetGlobalInfo");

array<VersionInfo^>^ args = gcnew array<VersionInfo^>(1)
{
    vi
};

auto result = m_Engine->Operations->Invoke(function, args);

And finally, the Python code:

def GetGlobalInfo(info):
    info.Major = 55
    return info.Major

The return value in result is not 55 as expected, but 12345. Can anybody please help me to find out, why the value is not changed from Python code? Thanks

1 Answer 1

2

I don't know if this is the cause of your problem, but:

public value struct VersionInfo

vs

VersionInfo^ vi
array<VersionInfo^>^

These two things are in conflict: value struct in C++/CLI defines a value type, not a reference type, so you don't want to use the ^ on it. It is legal to define a variable like that in C++/CLI, but it's very non-standard, and you can't even have a variable like that in C#.

Try it without the ^, and see what your result is. Be careful, though, because now inserting vi into the array will make a duplicate of vi, which would get modified independently.

Alternatively, you could change VersionInfo to be public ref class, and then the rest of your code is correct & standard.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I replaced value with ref in structure definition and it's working now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.