使用Ctypes配置DLL函数

问题描述 投票:0回答:1

我有一个共享库文件(Windows DLL),其中包含约50个函数。 DLL中的函数具有需要使用.argtypes和.restype配置的返回值和参数。我想创建一个模块,可以将其导入执行配置的python程序中。例如,以下代码在我的程序中运行正常(打开,关闭,保存是“ mydll”的示例函数:

import ctypes as ct
mylib = ct.cdll.LoadLibrary("mydll")

mylib.Open.argtypes = [ct.c_char_p] 
mylib.Open.restype = ct.c_int

mylib.Close.argtypes = [ct.c_int] 
mylib.Close.restype = ct.c_int

mylib.Save.argtypes = [ct.c_int] 
mylib.Save.restype = ct.c_int

#continue for 50 or so more functions

我想创建一个可以为此代码导入的程序包或模块,而不是将其包含在每个将使用“ mydll”的程序的开头。 Python中正确的方法是什么?

ctypes
1个回答
0
投票

我能够通过编写一个binding.py文件来解决此问题,该文件包含库mydll中每个函数的功能。

所以binding.py看起来像这样:

import ctypes as ct
mylib = ct.cdll.LoadLibrary("mydll")

def func1():
    mylib.func1().argtypes = [ct.c_char_p] 
    mylib.func1().restype = ct.c_int
    return mylib.func1()

def func2():
    mylib.func2().argtypes = [ct.c_int, ct.c_char_p, ct.POINTER(ct.c_double)]
    mylib.func2().restype = ct.c_int
    return mylib.func2()

def func3():
    mylib.func3().argtypes = []
    mylib.func3().restype = ct.c_int
    return mylib.func3()

The fundamental data types for the argument and return values can be found here:
[cytpes fundamental data types][1]


  [1]: https://docs.python.org/3/library/ctypes.html
© www.soinside.com 2019 - 2024. All rights reserved.