gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:32:04 25 4
gpt4 key购买 nike

我有 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/

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