gpt4 book ai didi

python - swig:扩展类模板以提供 __str__

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:53:11 25 4
gpt4 key购买 nike

假设你有一个模板类 Foo,你想用 Swig 透明地包装它以便打印类:

>>> from example import *
>>> f = Foo2()
>>> print(f)
In Foo class!

我关注了this postthis one .所以我的头文件是:

#include <iostream>

template <int d> class Foo {

public:

friend std::ostream &operator<<(std::ostream &os, const Foo &m) {
os << "Inside Foo class!" << std::endl;
return os;
}
};

还有我的界面文件:

%{
#include <sstream>
#include <iostream>
#include "foo.hpp"
%}

%include "std_iostream.i"

// Try grabbing it unmodified
%include "foo.hpp"


/* Instantiate a few different versions of the template */
%template(Foo2) Foo<2>;
%template(Foo3) Foo<3>;


%extend Foo<2> {

const char *__str__() {

std::ostringstream oss(std::ostringstream::out);
oss << *self;
return oss.str().c_str();
}
};

所以这工作得很好,我可以像以前一样打印对象,但我想将它概括为模板参数的任何值,因为为每个模板参数复制该代码没有意义。我在接口(interface)文件中尝试了以下内容,但没有成功:

template <int d> class Foo {

public:

%extend {
const char *__str__() {

std::ostringstream oss(std::ostringstream::out);
oss << *self;
return oss.str().c_str();
}
}
};

最佳答案

您应该能够%extend主模板,从其定义之外,通过省略模板参数列表:

%extend Foo {
const char *__str__() {
std::ostringstream oss(std::ostringstream::out);
oss << *self;
return oss.str().c_str();
}
};

%template(Foo2) Foo<2>;
%template(Foo3) Foo<3>;

或者您可以使用 SWIG 宏一次性包装和扩展每个特化:

%define WRAP_FOO(N)

%template( Foo ## N ) Foo<N>;

%extend Foo<N> {
const char *__str__() {
std::ostringstream oss(std::ostringstream::out);
oss << *self;
return oss.str().c_str();
}
};

%enddef

/* Instantiate a few different versions of the template */
WRAP_FOO(2)
WRAP_FOO(3)

请注意,在任何一种情况下,您都会通过返回之前销毁的 std::string.c_str() 结果来导致未定义的行为函数返回。

关于python - swig:扩展类模板以提供 __str__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25246440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com