如何从Python代码中获取char指针的值

2024-05-14 15:49:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在Python上使用C库。 然后,我想从C库fanction获取消息(char*)。在

我写了这些代码。 我得到了结果值(double*result_out),但我没有收到消息。 此代码显示“c_char_p(None)”。在

有什么想法吗?在

我使用python3.6和ubuntubash。在

C(利伯迪夫)公司名称:

#define ERROR -1
#define OK     0

int div (double x, double y, char *msg, double *result_out) {
    static char *err_msg = "0 div error"; 
    if(y == 0) {
        msg = err_msg;
        return ERROR;
    }
    *result_out = x/y;
    return OK;
}

Python:

^{pr2}$

Tags: 代码divnone消息returnokmsgerror
2条回答

要将值作为输出参数返回,需要传递指向返回值类型的指针。就像您使用double*来接收一个double,您需要一个char**来接收char*

#ifdef _WIN32
#   define API __declspec(dllexport)
#else
#   define API
#endif

#define OK     0
#define ERROR -1

API int div(double x, double y, char** ppMsg, double* pOut)
{
    static char* err_msg = "0 div error";
    if(y == 0)
    {
        *ppMsg = err_msg;
        return ERROR;
    }
    *pOut = x / y;
    return OK;
}

在Python中,还需要声明参数类型,否则Python将默认情况下将值封送到C中,这将中断double,并可能中断{},具体取决于操作系统的指针实现:

^{pr2}$

输出:

b'0 div error'

这里的主要问题是你的C被破坏了。为msg参数赋值不会在调用方端执行任何可见的操作(就像在Python函数中尝试赋值给参数一样)。在

如果您想使错误消息字符串对div的调用方可用,则需要使用char**,而不是char*,并分配给*msg。在Python端,您将传递类似byref(errmsg)的内容。在

除此之外,您还需要在lib.div上设置argtypesrestype,否则Python将不知道如何正确传递参数。在

相关问题 更多 >

    热门问题