c++ - Python 参数类型 C++ 签名

标签 c++ python types signature

我有 2 个问题,都与 Python 和 C++ 之间的参数如何混合有关...我在 C++ 中有一个函数,我从 python 调用它,我的函数接受日期和字符串。

Python str 和 C++ 一样吗

class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >

其次,我的函数需要一个类型为 class boost::gregorian::date 的日期,有谁知道我如何在 python 中给出一个可以使用正确签名读取的日期?

非常感谢帮助!我希望这是一个相当简单的问题,我只是对不同类型的签名不是很有经验(这对我目前链接 Python 和 C++ 的实验来说不是个好兆头)!

最佳答案

假设您正在使用 boost::python,让我告诉您如何处理这些情况。与其让 boost::python 自动包装您的函数,不如提供您自己的包装:

    namespace {

        void Foo_methodUsingDate( Foo* pointer, const object& dateObject )
        {
            boost::gregorian::date date = convertFromPython( dateObject );

            pointer->methodUsingDate( date );
        }
    }

    void wrap_Foo()
    {
        class_< Foo >( "Foo" )
            .def( "bar",
                & Foo::bar
                )
            .def( "foobar",
                & Foo::foobar
                )
            .def( "methodUsingDate",
                & Foo_methodUsingDate
                )
            ;
    }

当然,您需要提供一种将 boost::python::object 转换为 boost::gregorian::date 对象的方法。你必须决定如何处理这个。例如,您可以假设参数是三个整数的序列,或者您可以允许以更复杂的方式传递参数,或者定义一个新类来包装公历日期及其所有方法并将其直接公开给 Python。

关于您的第一个问题,当使用 boost::python 时,std::string 会自动转换为 Python 字符串或从 Python 字符串转换为字符串。

关于c++ - Python 参数类型 C++ 签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7917178/

相关文章:

c++ - 如何有效地组装 FEM 稀疏矩阵

python - numpy 基于 Mx1 矩阵创建 Mx2 矩阵

javascript - 将RSA加密的JavaScript代码翻译为Python

C# 类型对象指针

javascript - 目前是否有将两个或多个字符串文字类型连接到 TypeScript 中的单个字符串文字类型的方法?

c++ - 将 CGAL 与四元数结合起来合乎逻辑吗

c++ - std::map lower_bound 没有返回正确的值

c++ - "Warning : No return statement in function returning non-void"是什么意思?

python - abaqus脚本: TypeError: cannot concatenate 'str' and 'Set' objects

vba - $符号在VBA中有什么作用?