【问题标题】:Convert Python long integer to C char array将 Python 长整数转换为 C 字符数组
【发布时间】:2012-04-21 23:12:09
【问题描述】:

我正在使用 Python/C API,并且希望 C 函数采用 Python 长整数参数 nPyLong,并将其转换为以 10 为底的字符数组 nString。这是一个 sn- p 我想做的事。

PyObject *nPyLong;
PyArg_ParseTuple(args, "O", nPyLong);

PyLong_Check(nPyLong) // returns true

const char *nString;
// This function doesn't exist but demonstrates the functionality
PyLong_AsCharArray(&nString, nPyLong, 10);

API 参考中提到了一个函数 PyObject* PyLong_FromString(char *str, char **pend, int base),它将 C char 数组转换为 Python 长整数,给定任意基数,但我找不到执行相反操作的函数。

这可能吗?一种想法是将 Python 长整数转换为 Python 字符串对象,然后转换为 C 字符数组,但也没有字符串函数可以处理长整数。似乎 C 处理 Python long int 的唯一方法是转换为 C int 类型,所有这些都会在我的应用程序中溢出。

【问题讨论】:

    标签: python c python-c-api python-c-extension


    【解决方案1】:

    使用PyObject_Str()(或PyObject_Bytes())并将结果对象转换为char*

    【讨论】:

    • 哇,这比我想象的要容易得多。它甚至不返回后缀“L”!
    猜你喜欢
    • 2018-10-07
    • 2014-03-28
    • 1970-01-01
    • 2021-02-28
    • 2012-02-23
    • 1970-01-01
    • 2016-04-15
    • 2011-08-13
    • 2018-05-18
    相关资源
    最近更新 更多