将C++/CLI结构传递给IronPython的PythonFunction

2024-10-03 21:35:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我从C++ + CLI开始与iRyPython结合: 我在Python代码中遇到了托管结构的问题。 我的结构像这样

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

将此结构传递给Python如下

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);

最后,Python代码:

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

result中的返回值不是预期的55,而是12345。 有人能帮我找出为什么Python代码中的值没有改变吗? 谢谢


Tags: 代码infoargsfunction结构arraysystemruntime
1条回答
网友
1楼 · 发布于 2024-10-03 21:35:20

我不知道这是否是你问题的原因,但是:

public value struct VersionInfo

VersionInfo^ vi
array<VersionInfo^>^

这两个事物有冲突:C++中的^ {CD1>}定义了一个值类型,而不是引用类型,因此,不希望在其上使用^ {CD2>}。这是法律> EME>在C++中定义了一个类似的变量,但它非常不规范,甚至在C语言中甚至没有这样的变量。你知道吗

不用^试试,看看结果如何。不过,要小心,因为现在将vi插入数组将生成vi的副本,该副本将被独立修改。你知道吗

或者,您可以将VersionInfo更改为public ref class,然后代码的其余部分是正确的&标准的。你知道吗

相关问题 更多 >