SWIG:结构中的自定义类型和python中的赋值 我的C++代码有这样的东西: struct Data { CustomType member; }; %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"); } } }
我的swig.i文件具有%typemapin和%typemapout,用于将Python字符串转换为CustomType和从CustomType转换为Python字符串。这对于参数和返回值来说工作正常 在python中,我执行以下操作:SWIG:结构中的自定义类型和python中的赋值 我的C++代码有这样的东西: struct Data { CustomType member; }; %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"); } } },python,c++,swig,Python,C++,Swig,我的swig.i文件具有%typemapin和%typemapout,用于将Python字符串转换为CustomType和从CustomType转换为Python字符串。这对于参数和返回值来说工作正常 在python中,我执行以下操作: d = Data() d.member = "Hello" python在运行时给了我这个错误: TypeError:在方法“Data\u member\u set”中,参数2的类型为“CustomType*” 我尝试了以下方法,但没有效果: %typemap
d = Data()
d.member = "Hello"
python在运行时给了我这个错误:
TypeError:在方法“Data\u member\u set”中,参数2的类型为“CustomType*”
我尝试了以下方法,但没有效果:
%typemap(memberin) CustomType
{
$target = *$source;
}
如何允许python让我分配给该成员?如果可以从字符串创建CustomType,您应该可以这样做
d.member = CustomType("Hello")
如果失败,那么您没有通过.i文件导出CustomType,或者它没有接受字符串的构造函数 你需要这样写:
struct Data
{
CustomType member;
};
%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");
}
}
}
这意味着:
Python不允许重写assignemet运算符。相反
其中,SWIG为您的应用程序中所有可能的分配生成包装函数
C++代码。在任何一个地方
它注入了包装函数的调用。
使用上面的“类型映射”,可以初始化对象
从a CustomType和b内置Pyton创建的CustomType
一串
“typemap”中的代码只是
SWIG正在生成包装器finction。
在包装函数中定义CustomType的局部变量。
第一行中的代码是本地代码
作用域为整个函数的变量。
我建议您打开*_pywrap.cxx文件,该文件由SWIG生成,并根据您的“类型映射”检查它实际生成的内容
有关更多详细信息,请参阅官方文档:此解决方案不适用于我,因为CustomType未向python公开-在python中,我们只使用python str类型。正在替换自定义类型。。。用str。。。不起作用。@njaard那么您希望如何分配给它?我希望它能够从python str转换,就像我将str作为参数传递给接受CustomType的函数一样