首页 > 解决方案 > PYthon ctypes 'TypeError' LP_LP_c_long 实例而不是 _ctypes.PyCPointerType

问题描述

我尝试使用用 C++ 编写的 dll。它有这个功能:

bool PMDllWrapperClass::GetDeviceList(DEVICE** pDeviceArray, int* nDeviceCount, LAN_DEVICE** pLanDeviceArray, int LanDeviceCount, int InterfaceTypeToSearch)

我试过了:

cP = ctypes.POINTER(ctypes.POINTER(ctypes.c_int64))
cIP = ctypes.POINTER(ctypes.c_int32)
cLP = ctypes.POINTER(ctypes.c_int32)
cDC = ctypes.c_int32()
cIS = ctypes.c_int32()


resultgetdev = PMDll.GetDeviceList(cP, cIP, cLP, cDC, cIS)

但它说:

ctypes.ArgumentError: argument 1: <class 'TypeError'>: expected LP_LP_c_long instance instead of _ctypes.PyCPointerType

我也尝试过使用双指针,但没有奏效。我可以用 ctypes 解决它还是不可能?

标签: pythondllargumentsctypes

解决方案


错误消息是由于传递类型而不是实例。您应该声明参数类型和返回类型,以便 ctypes 可以仔细检查传递的值是否正确。

这需要更多信息才能准确,但您需要的最低要求是:

测试.cpp

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

struct DEVICE;
struct LAN_DEVICE;

extern "C" __declspec(dllexport)
bool GetDeviceList(DEVICE** pDeviceArray, int* nDeviceCount, LAN_DEVICE** pLanDeviceArray, int LanDeviceCount, int InterfaceTypeToSearch) {
    return true;
}

测试.py:

from ctypes import *

class DEVICE(Structure):
    _fields_ = () # members??

class LAN_DEVICE(Structure):
    _fields_ = () # members??

dll = CDLL('./test')
dll.GetDeviceList.argtypes = POINTER(POINTER(DEVICE)), POINTER(c_int), POINTER(POINTER(LAN_DEVICE)), c_int, c_int
dll.GetDeviceList.restype = c_bool

device_list = POINTER(DEVICE)()     # create instances to pass by reference for output(?) parameters
landev_list = POINTER(LAN_DEVICE)()
dev_count = c_int()

lan_count = 5    # ??
search_type = 1  # ??

result = dll.GetDeviceList(byref(device_list),byref(dev_count),byref(landev_list),lan_count,search_type)

推荐阅读