使用ctypes访问dll会使python.exe崩溃

2024-06-26 11:19:22 发布

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

我想用python和ctypes访问dll的函数。我使用python 3.6.1 32位,Visual Studio代码在Win10 64位上运行。 dll是测试软件的一部分,进行一些配置并调用一些进一步的dll。 它创建一个映像,将映像加载到视频测试硬件,然后使用该映像测试DUT。 我没有访问dll的权限,无法修改它。只有一个.h可用

首先,我想描述.h文件的相关部分:

#ifdef __cplusplus
extern "C" {
#endif

#ifdef BUILD_INTERFACE_DLL
#define EXPORT_TO_INTERFACE_DLL __declspec(dllexport)
#else
#define EXPORT_TO_INTERFACE_DLL __declspec(dllimport)
#endif

struct Interface_t;
typedef struct Interface_t Interface;
EXPORT_TO_TESTINTERFACE_DLL Interface * createInterface(const char* versionTag);
EXPORT_TO_TESTINTERFACE_DLL int initConnection(Interface* Interface, const char * deviceId);
EXPORT_TO_TESTINTERFACE_DLL int generateImage(Interface* Interface,char* pathToImage, size_t maxFileNameLength);

以下是我的Python脚本:

import ctypes as ct
lib = ct.CDLL("./TestInterface.dll")

libEcu.createInterface.restype = ct.POINTER(ct.c_int32)
libEcu.createInterface.argtypes = [ct.c_char_p]
libEcu.initConnection.restype = ct.c_int32
libEcu.initConnection.argtypes = [ct.POINTER(ct.c_int32), ct.c_char_p]
libEcu.generateImage.restype = ct.c_int32
libEcu.generateImage.argtypes = [ct.POINTER(ct.c_int32), ct.c_char_p, ct.c_int32]

CamDeviceId = (b"SomeConfigString")
MaxFileNameLength = 1000
pathToImage = (b"generatedTestImage.bmp")
versionTag = (b"SomeVersionString")

Interface = lib.createInterface(versionTag)
lib.initConnection(Interface, CamDeviceId)
lib.generateImage(Interface, pathToImage, MaxFileNameLength)

这是我的问题: createInterface和initConnection工作正常。我在终端上收到一些消息,确认接口已创建,连接已成功初始化

调用“generateImage”时,我得到错误消息“Python停止工作”,并带有调试或关闭程序的选项。Visual Studio代码中没有错误消息。 函数正确执行,生成图像并发送到测试硬件。 由于我没有进一步的可能性在VisualStudio代码中进行调试,我查看了Windows的事件查看器。崩溃的应用程序是“python.exe”,崩溃的模块是“python.dll”,异常代码是“0xc0000005”

在这个问题上有什么帮助吗? 我做错什么了吗?我对Python还是个新手。 使用C程序访问dll时,每个函数都能正常工作

谢谢你和问候


Tags: to函数代码libexportinterfacedllct
1条回答
网友
1楼 · 发布于 2024-06-26 11:19:22

@MarkTolonen

替换

(b“generatedTestImage.bmp”)

创建字符串缓冲区(b“generatedTestImage.bmp”,MaxFileNameLength)

解决了这个问题

问题是缓冲区的长度。它需要定义,不能太小(30次碰撞,50次工作)。我将其设置为MaxFileNameLength=1000,并将其复制&;粘贴自某个工作C代码示例

多谢各位

相关问题 更多 >