传入单个int类型值的指针
test_dll.dll文件添加如下C代码
#include <stdio.h>
extern "C"
{
_declspec(dllexport) void fun(int *x)
{
*x = 100;
}
}
python调用test_dll.dll中函数:使用ctypes.byref(…)包装ctypes.c_int(…)传入int*指针
In [1]:import ctypes
In [2]:import win32api
In [3]:test_dll_path = "test_dll.dll"
In [4]:test_dll_obj = ctypes.windll.LoadLibrary(test_dll_path)
In [5]:c_int_param = ctypes.c_int(123)
In [5]:test_dll_obj.fun(ctypes.byref(c_int_param))
In [6]:print(c_int_param.value)
Out[6]:100
In [7]:win32api.FreeLibrary(test_dll_obj._handle)
可以看到python中一个int变量原值为123,在传入test_dll中对应指针后,在test_dll中通过内存地址将值成功修改为100。
其它基本类型的指针传入方式类似,都是通过ctypes.byref关键字.
ctypes官方详细文档地址:
https://docs.python.org/zh-cn/3/library/ctypes.html#passing-pointers-or-passing-parameters-by-reference