ctypes: OSError:异常:读取0x00000001时访问冲突

2 投票
2 回答
8412 浏览
提问于 2025-04-20 11:45

我正在尝试通过一个C语言的动态链接库(dll)用Python与高压电源(HV-Supply)进行通信。我能成功运行最简单的函数。但是,当我调用更复杂的函数CAENHVInitSystem时,出现了一个错误:OSError: exception: access violation reading 0x00000001。我对Python中的ctypes还比较陌生。根据我的了解,这个错误可能是因为我的某些参数类型不对。但是我该如何进一步调试,以准确找出哪个参数有问题呢?有没有人能看到我的错误?

提前谢谢大家

import os
from ctypes import *

bib = CDLL("CAENHVWrapper")

ret = bib.CAENHVLibSwRel()  # This call works
print(c_char_p(ret)) 

sysType = c_int(1) #SY2527
link = c_int(0) #TCP/IP
#arg = c_char_p(b'149.217.10.241')  #i change it for test to c_void_p but later the arg should be the ip adress
arg = c_void_p()                   
user = c_char_p(b'admin')
passwd = c_char_p(b'admin')
sysHndl = c_int()

# c function definition in the header file
#CAENHVLIB_API CAENHVRESULT CAENHV_InitSystem(
#   CAENHV_SYSTEM_TYPE_t system,
#   int LinkType,
#   void *Arg,
#   const char *UserName,
#   const char *Passwd,
#   int *handle);

# definition of the enum of the first argument
#typedef enum {
#   SY1527      = 0,
#   SY2527      = 1
#} CAENHV_SYSTEM_TYPE_t;

bib.CAENHVInitSystem.argtypes = [c_int, c_int, c_void_p, c_char_p, c_char_p,     POINTER(c_int)]
ret = bib.CAENHVInitSystem(sysType, link, arg, user, passwd, byref(sysHndl))

print(ret)
print(bib.CAENHV_GetError(sysHndl))

2 个回答

0

在我的Ctypes设置中,当我不小心同时运行了多个程序实例时,出现了这个错误。

简单来说,我忘记关闭之前的程序实例,它们还在占用DLL文件,所以当最新的版本想要访问这个文件时,就无法成功了。

3

CAENHVInitSystem的第一个参数是系统名称,类型是const char*。你错误地传入了一个值为1的整数。当CAENHVInitSystem把这个整数当作指针时,它试图去读取地址1的内存,这就导致了错误。你需要把第一个参数的类型改成c_char_p,并传入文本。

据我所知,这个函数有5个参数,而不是6个,所以我相信你还有其他错误,而不仅仅是上面提到的那个。

将来在询问关于二进制互操作的问题时,你必须提供接口两边的详细信息。我通过在网上搜索CAENHVInitSystem来回答这个问题,希望找到的声明与你使用的匹配。但也许并不是这样。你应该有CAENHVInitSystem的真实声明,这个信息非常重要,应该在问题中提供。

撰写回答