gpt4 book ai didi

python - 如何使用 ctypes 从 Python 代码中获取 char 指针的值

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:39 24 4
gpt4 key购买 nike

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

这些代码是我写的。我得到了 result value(double* result_out) ,但没有收到消息。此代码显示“c_char_p(None)”。

有什么想法吗?

我使用 Python 3.6 和 Ubuntu Bash。

C(libdiv.so):

#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:

from ctypes import *

lib = cdll.Loadlibrary('libdiv.so')
errmsg = c_char_p()
result = c_double(0)
rtn = lib.div(10, 0, errmsg, byref(result))

if rtn < 0:
print (errmsg) # None
else :
print (result.value) # OK.

最佳答案

要返回一个值作为输出参数,您需要传递一个指向返回值类型的指针。就像您使用 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 作为 c_int,这会破坏 double 并且可能根据操作系统的指针实现来中断 char*:

from ctypes import *

lib = CDLL('test')
lib.div.argtypes = c_double,c_double,POINTER(c_char_p),POINTER(c_double)
lib.div.restype = c_int

errmsg = c_char_p()
result = c_double()
rtn = lib.div(10, 0, byref(errmsg), byref(result))

if rtn < 0:
print(errmsg.value)
else:
print(result.value)

输出:

b'0 div error'

关于python - 如何使用 ctypes 从 Python 代码中获取 char 指针的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54407844/

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