有没有办法(在 C++ 中,而不是在 Python 中)从外部为 Boost::Python 中的类添加函数模板的额外实例化(通过注入(inject)、重新打开定义、注册所需的实例化等)?
给定一个包含函数模板成员的类(不是类模板),我想使用 Boost::Python 生成 Python 绑定(bind)。
但是,由于我正在编写一个库,所以我事先并不知道成员函数将使用哪些模板参数进行调用。这意味着,我不能在 Boost::Python 类定义中列出它们。
假设我们有一个类 TheClass,它有函数模板(带重载),以及两个测试类 SomeClass 和 OtherClass,如下所示:
#include <iostream>
#include <string>
class SomeClass
{
public:
std::string Name()
{
return "SomeClass";
}
};
class OtherClass
{
public:
std::string Name()
{
return "OtherClass";
}
};
class TheClass
{
public:
template <class T>
void Foo (T& arg)
{
std::cout << "Called Foo(" << arg.Name() << ")" << std::endl;
}
template <class T>
void Bar (T& arg, std::string param)
{
std::cout << "Called Bar(" << arg.Name() << ", " << param << ")" << std::endl;
}
template <class T>
void Bar (T& arg, int param)
{
std::cout << "Called Bar(" << arg.Name() << ", " << param << ")" << std::endl;
}
};
然后我使用这段代码将上述所有内容导出到 Python:
#include <boost/python.hpp>
#define GENERATE_THE_CLASS_METHODS(classname) \
.def( \
"Foo", \
( void ( TheClass::* )( classname& ))( &TheClass::Foo ), \
( boost::python::arg("arg") ) \
) \
.def( \
"Bar", \
( void ( TheClass::* )( classname&, std::string ))( &TheClass::Bar ), \
( boost::python::arg("arg"), boost::python::arg("param") ) \
) \
.def( \
"Bar", \
( void ( TheClass::* )( classname&, int ))( &TheClass::Bar ), \
( boost::python::arg("arg"), boost::python::arg("param") ) \
)
BOOST_PYTHON_MODULE(my_module)
{
boost::python::class_< TheClass > ( "TheClass" )
GENERATE_THE_CLASS_METHODS(SomeClass)
GENERATE_THE_CLASS_METHODS(OtherClass)
// This is the interesting part: all instantiations of the function
// templates have to be inserted here. How can this be avoided
// so that new classes can also be used?
;
boost::python::class_< SomeClass > ( "SomeClass" );
boost::python::class_< OtherClass > ( "OtherClass" );
}
(附带问题:我在这里使用宏是为了避免出于维护原因的重复代码。是否有更漂亮的 C++ 式实现方法?)
上面的代码使用 Clang 和 C++11、Boost 1.57.0 和 Python 2.7.6 进行编译。它适用于此测试脚本:
#!/usr/bin/python
from my_module import *
s = SomeClass()
o = OtherClass()
t = TheClass()
t.Foo(s)
t.Foo(o)
t.Bar(s, 42)
t.Bar(o, 42)
t.Bar(s, "Hello World")
t.Bar(o, "Hello World")
产生这个结果:
Called Foo(SomeClass)
Called Foo(OtherClass)
Called Bar(SomeClass, 42)
Called Bar(OtherClass, 42)
Called Bar(SomeClass, Hello World)
Called Bar(OtherClass, Hello World)
在示例中,Foo() 和 Bar() 函数模板的实例是在 Boost::Python 类定义中创建的(请参阅源代码中的注释)。这意味着,库的用户在不修改这段代码的情况下无法添加新实例。
因此,我正在寻找的是一种方法
最后,图书馆的用户应该能够做这样的事情:
class AnotherClass
{
public:
std::string Name()
{
return "AnotherClass";
}
};
add_to_the_class(AnotherClass);
// or
add_to_class_definition<AnotherClass>("TheClass");
// or whatever works...
这有可能吗?还有其他方法可以实现类似的目标吗?
最佳答案
一段时间后,我找到了解决方案,并认为其他人也可能会感兴趣。
其实很简单:boost::python::class_定义返回(当然)类型为 boost::python::class_< TheClass > 的类实例.这可以被存储,所以我们可以稍后向它添加成员定义:
static auto the_class_ = boost::python::class_< TheClass > ( "TheClass" )
// add some .def(...) and so on here, if needed
;
template <class T>
void add_to_the_class()
{
the_class_
.def(
"Foo",
( void ( TheClass::* )( T& ))( &TheClass::Foo ),
( boost::python::arg("arg") )
)
.def(
"Bar",
( void ( TheClass::* )( T&, std::string ))( &TheClass::Bar ),
( boost::python::arg("arg"), boost::python::arg("param") )
)
.def(
"Bar",
( void ( TheClass::* )( T&, int ))( &TheClass::Bar ),
( boost::python::arg("arg"), boost::python::arg("param") )
)
;
}
现在我们可以根据需要从外部向这个定义添加任意多的额外重载:
add_to_the_class<AnotherClass>();
这也摆脱了丑陋的宏。
这一切都有效,因为与 Python 的实际绑定(bind)是在运行时创建的。在您的 boost::python 绑定(bind)代码中,您实际上只是定义了一些类和函数——它们在 main() 之前调用以启动您的 C++ 代码和 Python 解释器之间的实际连接。
我认为,这在 boost::python 帮助中没有很好的记录。我花了一段时间才弄明白这一点。一开始,我认为 boost::python 以某种方式(通过一些模板魔术)在编译期间生成了绑定(bind)。如果这是真的,上面的解决方案将不起作用。事后看来,这对我来说已经很清楚了。
此外,这种洞察力(绑定(bind)是在运行时完成的,使用您提供的定义)也让我想到了编写一个静态寄存器类来收集要导出到 Python 的类。这将有助于我的图书馆更进一步,因为我不必扩展主要的 BOOST_PYTHON_MODULE每个新类的定义,而是简单地将类注册到静态寄存器(可能再次使用一些宏......)。但这是 future 的工作......现在问题已经解决了!
关于python - 带有函数模板的 Boost::Python 类:如何从外部添加实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30463563/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/
我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为