用Python从c++dll返回数据

2024-06-26 14:08:32 发布

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

我正在编程一个与3M文档扫描仪的接口。在

我试图调用一个名为MMMReader_GetData的函数

MMMReaderErrorCode MMMReader_GetData(MMMReaderDataType aDataType,void* DataPtr,int* aDataLen);

说明: 从文档中读取数据项后,可以通过此API获取数据项。
aDataPtr参数中提供的缓冲区将与数据一起写入,aDataLen将更新为 数据的长度。在

问题是如何创建void* DataPrt,以及如何获取数据。在

我试着:

from ctypes import *
lib=cdll.LoadLibrary('MMMReaderHighLevelAPI.dll')
CD_CODELINE = 0
aDataLen = c_int()
aDataPtr = c_void_p()
index= c_int(0)

r = lib.MMMReader_GetData(CD_CODELINE,byref(aDataPtr),byref(aDataLen),index)

aDataLen始终返回值,但aDataPtr返回None

TIA公司


Tags: 数据文档indexlib编程cdint扫描仪
3条回答

你需要做的是分配一个“缓冲区”。缓冲区的地址将作为void*参数传递,而以字节为单位的缓冲区大小将作为aDataLen参数传递。然后函数将把它的数据放在你给它的缓冲区中,然后你就可以把数据从缓冲区中读回。在

<>在C或C++中,你会使用^ {CD2>}或类似的东西来创建缓冲区。当使用ctypes时,可以使用ctypes.create_string_buffer创建一个具有一定长度的缓冲区,然后将缓冲区和长度传递给函数。然后,一旦函数填充了它,就可以从创建的缓冲区中读取数据,缓冲区的工作方式类似于一个带有[]len()的字符列表。在

使用ctypes,最好定义参数类型和返回值以更好地进行错误检查,并且声明指针类型在64位系统上尤其重要。在

from ctypes import *

MMMReaderErrorCode = c_int  # Set to an appropriate type
MMMReaderDataType = c_int   # ditto...

lib = CDLL('MMMReaderHighLevelAPI')
lib.MMMReader_GetData.argtypes = MMMReaderDataType,c_void_p,POINTER(c_int)
lib.MMMReader_GetData.restype = MMMReaderErrorCode

CD_CODELINE = 0

# Make sure to pass in the original buffer size.
# Assumption: the API should update it on return with the actual size used (or needed)
# and will probably return an error code if the buffer is not large enough.
aDataLen = c_int(256)

# Allocate a writable buffer of the correct size.
aDataPtr = create_string_buffer(aDataLen.value)

# aDataPtr is already a pointer, so no need to pass it by reference,
# but aDataLen is a reference so the value can be updated.
r = lib.MMMReader_GetData(CD_CODELINE,aDataPtr,byref(aDataLen))

返回时,您可以通过字符串切片访问缓冲区的返回部分,例如:

^{pr2}$

您的代码有几个问题:

  1. 您需要分配aDataPtr指向的缓冲区。在
  2. 您需要在aDataLen中传递缓冲区长度。根据[1],如果缓冲区不够大,MMMReader_GetData将根据需要重新分配它。在
  3. 您应该直接传递aDataPtr,而不是byref。在
  4. 您将根据您提供的MMMReader_GetData的方法描述符向方法传递一个额外的参数(index参数)。在

尝试以下操作:

import ctypes

lib = ctypes.cdll.LoadLibrary('MMMReaderHighLevelAPI.dll')

CD_CODELINE = 0
aDataLen = ctypes.c_int(1024)
aDataPtr = ctypes.create_string_buffer(aDataLen.value)

err = lib.MMMReader_GetData(CD_CODELINE, aDataPtr, ctype.byref(aDataLen))

然后可以将缓冲区的内容作为常规字符数组读取。实际长度将在aDataLen中返回给您。在

[1]3百万页的读者程序员指南:https://wenku.baidu.com/view/1a16b6d97f1922791688e80b.html

相关问题 更多 >