[英]Python ctypes: c_char_p not returning the correct value
I'm new to Ctypes and trying to make a wrapper to use some dll functions but i'm facing a problem first here is the code我是 Ctypes 的新手,并试图制作一个包装器来使用一些 dll 函数,但我首先遇到了一个问题,这里是代码
C function structure C function结构
long func(char *pID);
Python code Python代码
lib = WinDLL("some.dll")
lib.func.restype = c_long
lib.func.argtypes = [c_char_p]
ID = c_char()
lib.func(byref(ID))
print(ID)
this outputs 8 which is correct but only the first character这输出 8 这是正确的,但只有第一个字符
the problem is I need the complete output not just the first char.问题是我需要完整的 output 而不仅仅是第一个字符。 I replaced it with c_char_p it give this c_char_p(925904440) which is a pointer but when I print its value (ID.value) it print an empty string while c_char was giving the correct value why?
我用 c_char_p 替换了它,它给出了这个 c_char_p(925904440) 这是一个指针,但是当我打印它的值(ID.value)时它打印一个空字符串,而 c_char 给出了正确的值,为什么?
also tried create_string_buffer(10) but gives an error也尝试了 create_string_buffer(10) 但给出了错误
expected LP_c_char_p instance instead of pointer to c_char_Array_10预期 LP_c_char_p 实例而不是指向 c_char_Array_10 的指针
Notice: I'm writing a J2534 wrapper since all the libraries that I had found have some kind of error tried python libs and C# libs if you know or have a working J2534 library then send me its link注意:我正在编写一个 J2534 包装器,因为我发现的所有库都尝试了 python 库和 C# 库,如果你知道或有一个工作的 J2534 库,那么给我它的链接
You could use create_string_buffer.您可以使用 create_string_buffer。 Documentation says:
文档说:
ctypes.create_string_buffer(init_or_size, size=None)
ctypes.create_string_buffer(init_or_size, size=None)
This function creates a mutable character buffer.
这个 function 创建一个可变字符缓冲区。 The returned object is a ctypes array of c_char.
返回的 object 是 c_char 的 ctypes 数组。
init_or_size must be an integer which specifies the size of the array, or a bytes object which will be used to initialize the array items.
init_or_size 必须是指定数组大小的 integer,或者是用于初始化数组项的字节 object。
see https://docs.python.org/3/library/ctypes.html#ctypes.create_string_buffer见https://docs.python.org/3/library/ctypes.html#ctypes.create_string_buffer
An example could look like this:一个示例可能如下所示:
from ctypes import *
lib = cdll.LoadLibrary("some.dll")
lib.func.restype = c_long
lib.func.argtype = c_char_p
buf = create_string_buffer(9)
lib.func(buf)
print(buf.value.decode("utf-8"))
A simple test function on the C-side could look like this: C 端的简单测试 function 可能如下所示:
#include <string.h>
static const char some_data[] = "8.07.696";
long func(char *p) {
strcpy(p, some_data);
return 1L;
}
This prints the expected result to the debug console:这会将预期结果打印到调试控制台:
8.07.696
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.