【问题标题】:Calling a non-exported function in a DLL in Python在 Python 中调用 DLL 中的非导出函数
【发布时间】:2022-01-06 16:00:31
【问题描述】:

我正在使用 Python 并尝试执行 DLL 函数。如果它们被暴露,我可以通过它们的名字来执行函数:

# Load DLL into memory.

hllDll = ctypes.WinDLL ("mydll.dll")

# Set up prototype and parameters for the desired function call.

hllApiProto = ctypes.WINFUNCTYPE (
    ctypes.c_int,      # Return type.
    ctypes.c_void_p,   # Parameters 1 ...
    ctypes.c_void_p,
    ctypes.c_void_p,
    ctypes.c_void_p)   # ... thru 4.
hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0),

# Actually map the call ("HLLAPI(...)") to a Python name.

hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams)

hllApi(p1, p2, p3, p4)

但我想为非导出函数的地址创建一个funcptr。

在 C++ 中,我们可以这样做:(如果我没记错的话):

FUNCPTR(MYDLL, myFuncName, DWORD __stdcall, (DWORD arg1, DWORD arg2, DWORD arg3), <ADDR>)

有人知道 Python 中这个函数的等价物吗?

谢谢!

【问题讨论】:

  • 如果它没有被导出,它并不意味着从外部调用。请说明函数是如何定义的。

标签: python dll ctypes


【解决方案1】:

假设你以某种方式获得了函数的地址:

// test.c
int func(int a, int b) { return a + b; }

__declspec(dllexport)
void* get_func() { return (void*)func; }

然后:

# test.py
import ctypes as ct

dll = ct.CDLL('./test')
dll.get_func.argtypes = ()
dll.get_func.restype = ct.c_void_p

addr = dll.get_func()

ADD = ct.CFUNCTYPE(ct.c_int,ct.c_int,ct.c_int) # function prototype
add = ADD(addr)                                # function instance
print(add(2,3))

# In this case, can also just set the return type to the function prototype...
dll.get_func.restype = ADD
add = get_func()
print(add(2,3))

输出:

5
5

【讨论】:

    猜你喜欢
    • 2011-02-24
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多