在Stack Overflow问题中,在C++ 11中不允许重新定义lambda,为什么?,给出了一个不编译的小程序:
int main() {
auto test = []{};
test = []{};
}
Run Code Online (Sandbox Code Playgroud)
问题得到了回答,一切似乎都很好.然后是Johannes Schaub并做了一个有趣的观察:
如果你
+在第一个lambda之前放置一个,它会神奇地开始工作.
所以我很好奇:为什么以下工作呢?
int main() {
auto test = +[]{}; // Note the unary operator + before the lambda
test = []{};
}
Run Code Online (Sandbox Code Playgroud)
我目前正在使用Boost.Python,并希望得到一些帮助来解决一个棘手的问题.
上下文
当C++方法/函数暴露给Python时,它需要释放GIL(全局解释器锁)以让其他线程使用解释器.这样,当python代码调用C++函数时,解释器可以被其他线程使用.现在,每个C++函数看起来像这样:
// module.cpp
int myfunction(std::string question)
{
ReleaseGIL unlockGIL;
return 42;
}
Run Code Online (Sandbox Code Playgroud)
为了传递它来提升python,我做:
// python_exposure.cpp
BOOST_PYTHON_MODULE(PythonModule)
{
def("myfunction", &myfunction);
}
Run Code Online (Sandbox Code Playgroud)
问题
这个方案工作正常,但它暗示这module.cpp取决于Boost.Python没有充分理由.理想情况下,只python_exposure.cpp应该依赖Boost.Python.
解?
我的想法是用Boost.Function这样包装函数调用:
// python_exposure.cpp
BOOST_PYTHON_MODULE(PythonModule)
{
def("myfunction", wrap(&myfunction));
}
Run Code Online (Sandbox Code Playgroud)
这里wrap将负责在通话期间解锁GIL myfunction.这种方法的问题是wrap需要具有相同的签名,myfunction这几乎意味着重新实现Boost.Function...
如果有人对此问题有任何建议,我将非常感激.
我有一个struct包含C风格的数组数据成员.我想将这个结构体暴露给Python,并且这个数据成员可以作为Python中的列表访问.
struct S
{
char arr[4128];
};
void foo( S const * )
{}
BOOST_PYTHON_MODULE( test )
{
using namespace boost::python;
class_<S>( "S" )
.def_readwrite( "arr", &S::arr )
;
def( "foo", foo );
}
Run Code Online (Sandbox Code Playgroud)
上面的代码无法构建
error C2440: '=' : cannot convert from 'const char [4128]' to 'char [4128]'
Run Code Online (Sandbox Code Playgroud)
C风格的数组不可分配,因此错误很有意义.如果我将数据成员更改为普通char而不是数组,则代码将编译.
我无法用一个std::array或其他容器替换该数组,因为该结构正由C API使用.我能想到的唯一解决方案是编写几个包装器并执行以下操作
struct S1重复的,S除了它将有一个std::array而不是一个C风格的数组foo_wrapper接受a的A ,S1 const *将内容复制到S实例并调用footo_python_converter转换std::array为Python列表 …