【问题标题】:SWIG: custom types in structures and assignment in pythonSWIG:结构中的自定义类型和 python 中的赋值
【发布时间】:2014-05-16 22:12:59
【问题描述】:

我的 C++ 代码是这样的:

struct Data
{
    CustomType member;
};

我的 swig .i 文件有 %typemap(in) 和 %typemap(out) 来将 Python 字符串与 CustomType 相互转换(这对于参数和返回值都很好)

在我的 python 中,我这样做:

d = Data()
d.member = "Hello"

python 在运行时给了我这个错误: TypeError:在“Data_member_set”方法中,“CustomType *”类型的参数 2

我尝试了以下没有效果:

%typemap(memberin) CustomType
{
    $target = *$source;
}

如何让python让我分配给那个成员?

【问题讨论】:

    标签: python c++ swig


    【解决方案1】:

    如果可以从字符串创建CustomType,您应该可以这样做

    d.member = CustomType("Hello")
    

    如果失败,那么您还没有通过 .i 文件导出 CustomType,或者它没有接受字符串的构造函数。

    【讨论】:

    • 这个解决方案对我不起作用,因为 CustomType 没有暴露给 python - 在 python 中,我们专门使用 python str 类型。用 str(...) 替换 CustomType(...) 不起作用。
    • @njaard 那你希望如何分配给它?
    • 我希望它从 python str 转换,就像我将 str 作为参数传递给接受 CustomType 的函数时一样
    【解决方案2】:

    你需要这样写:

    %typemap(in) CustomType* (CustomType tmp, int res)
    // or even: %typemap(in) CustomType* ($*1_type tmp, int res)
    {
      if (PyString_Check($input))
      {
        tmp = (PyString_AsString($input));
        $1 = &tmp;
      }
      else
      {
        res = SWIG_ConvertPtr($input, (void **) &$1,$1_descriptor, 0 |  0 );
        if (!SWIG_IsOK(res)) {
          SWIG_exception_fail(SWIG_ArgError(res), "in method '" "$symname" "', argument " "$argnum"" of type '" "$1_type""'.\n"
            "  Possible argument types are: 'string' and '" "$*1_type" "'\n");
        }
      }
    }
    

    这意味着:

    1. Python 不允许您覆盖assignemet 运算符。反而 SWIG 为您的所有可能分配生成包装函数 C++ 代码。在每个“=”可以的地方 是它注入包装函数的调用。
    2. 使用上面的'typemap',你可以初始化一个对象 来自 a) CustomType 和 b) 内置 Pyton 的 CustomType 字符串。
    3. “typemap”中的代码只是 由 SWIG 生成的包装函数。
    4. 您在包装函数中定义了 CustomType 的局部变量。 第一行圆括号中的代码是本地的 范围是整个函数的变量。

    我建议您打开 *_pywrap.cxx 文件(该文件由 SWIG 生成)并根据您的“类型映射”检查它实际生成的内容。

    更多详情请查阅官方文档:http://www.swig.org/Doc1.3/SWIGDocumentation.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-24
      • 2011-04-15
      • 1970-01-01
      相关资源
      最近更新 更多