Python C++ 扩展编译器警告

标签 python c++

我在 C++ 扩展中有这样的东西:

char* kwlist[] = {"x", "W"};
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO", kwlist, &x, &W)) return NULL;

编译器提示:

warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]

消除此警告的最佳方法是什么?

我试过:

char const* kwlist[] = {"x", "W"};

但是失败了:

候选函数不可行:没有已知的从“const char [2]”到“char *”的转换

最佳答案

看起来您正试图迂腐地对 const-correct 进行一定程度的修正,而 Python 的 C API 却没有,即使是间接地通过在您的编译器上发出警告。您在这里有几个选择。 (请注意,我无法在我的编译器中重现您的警告,因此请仔细检查我的建议是否确实解决了问题。)

  • 丢弃创建时的警告:

    char* kwlist[] = { const_cast<char*>("x"), const_cast<char*>("W") };
    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO", kwlist, &x, &W)) return NULL;
    
  • 抛开使用中的错误:

    char const* kwlist[] = { "x", "W" };
    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO", const_cast<char **>(kwlist), &x, &W)) return NULL;
    
  • 根据需要使事物可变:

    char kw_x[] = "x";
    char kw_W[] = "W";
    char* kwlist[] = { kw_x, kw_W };
    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OO", kwlist, &x, &W)) return NULL;
    
  • 在全局或本地使特定警告静音:

    局部警告抑制的确切代码取决于编译器。我在下面列出了两种常见情况:

    GCC (感谢 Matt Joiner !)

    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wdeprecated-writable-strings"
    takes_ppchar(kwlist);         /* no diagnostic for this one */
    #pragma GCC diagnostic pop
    

    Visual Studio

    #pragma warning(push)
    #pragma warning(disable : ####)
    code_causing_warning(####)
    #pragma warning(pop)
    

丢弃 const 并不是普遍安全的,因此如果 PyArg_ParseTupleAndKeywords 实际上以非常量方式使用内容,前两种方法中的任何一种都可能合法地导致运行时失败。

如果您强烈怀疑(或更好地验证)PyArg_ParseTupleAndKeywords 以常量安全的方式使用您的参数(请求的权限多于它使用的权限),大多数方法都比技术上正确的第三种方法更简洁方法。

关于Python C++ 扩展编译器警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23664396/

相关文章:

c++ - 重新抛出异常保留回溯

python - 如何将 Dask 数据帧作为 dask-ml 模型的输入传递?

python - 尝试将通过social_django验证的用户添加到组时出现错误 `set object is not subscriptable`

python - 什么是 [ :] do?

c++ - C++中类字符串的内部结构

c++ - 将值从一个函数传递到另一个函数

c++ - 使用cin.get读取字符数组

python - 如果其中一项任务失败,Celery 链就会中断

python - (1,) 在 Python 中是什么意思?

c++ - 哪个 GUI 库用于开发 Mozilla Firefox?