Python中带有返回值的C#回调

2024-04-19 08:47:35 发布

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

我试图在DLL中调用以下函数,该函数(据我有限的理解)将回调作为参数

C#定义:

//Error handler
public delegate int FPtrErrorHandler(int ErrorType, int MessageType, int WhomToInform, String ErrorMessage);

//Desired function to call
[ DllImport ( Globals.LibDLLPath, CallingConvention = CallingConvention.Cdecl ) ]
public static extern int OpenLib(String TempDirectory, Bool IfCleanTempDir, FPtrErrorHandler ErrorHandler);

根据this SO entry,我创建了下面的Python代码:

import ctypes as c
from ctypes import *

@c.WINFUNCTYPE(c.c_int, c.c_int, c.c_int, c.c_int, c.c_char_p)
def FPtrErrorHandler(ErrorIdentifier, ErrorMessageType, WhomToInform, ErrorMessage):
    print(f'Error ID={ErrorIdentifier}, Type={ErrorMessageType}, WhomToInform={WhomToInform}, msg={ErrorMessage}')
    return 0

lib = windll.LoadLibrary('path_to_dll')

_OpenLib = lib[163]
_OpenLib.restype = c_int
_OpenLib.argtypes = [c_char_p, c_bool, c_void_p]
def OpenLib(TempDirectory,IfCleanTempDir):
    cb1 = FPtrErrorHandler
    return _OpenLib(TempDirectory, IfCleanTempDir, cb1)

n = OpenLib(r:'c:\temp',c_bool(True))

不幸的是,我收到了可怕的信息

ArgumentError: argument 1: <class 'TypeError'>: wrong type

提前谢谢你帮我做这件事。我真的很高兴学习ctypes,以及如何使用Python与令人惊叹的DLL进行交互


Tags: to函数stringerrorpublicctypesintdll
1条回答
网友
1楼 · 发布于 2024-04-19 08:47:35

天哪,我想这可能很容易

如果我将对函数的调用从

n = OpenLib(r:'c:\temp',c_bool(True))

n = OpenLib(rb:'c:\temp',c_bool(True))

它似乎起作用了。我刚刚在字符串前缀中添加了b修饰符

相关问题 更多 >