C.dll 如何将变量公开给 Python?
How can C.dll expose variable to Python?
我正在尝试将 C 主程序写入 dll,Python 将从该 dll 导入所有内容(包括所有变量和函数),并运行在 dll 中定义的函数。但是,我打算不仅将函数而且从 DLL 导出变量到 Python。
我了解如何使用 DLL 将函数公开给 Python,但我不确定如何使用 Python.
中的 Ctype 从 dll 访问变量
举个例子:
如果在 header 中,我们有 #DEFINE MAXDEVNUMBER 4。
当我使用 ctype print mydll.MAXDENUMBER 它给我一个错误。函数 'MAXDENUM' 未找到
您无法访问预处理器宏,因为它们不是从 DLL 中导出的。您只能访问导出的 C 函数和全局变量。
例如,test.c:
__declspec(dllexport) int b = 5;
__declspec(dllexport) int func(int a)
{
return a + b;
}
>>> from ctypes import *
>>> dll = CDLL('test')
>>> dll.func(1)
6
>>> x=c_int.in_dll(dll,'b') # access the global variable
>>> x.value
5
>>> x.value = 6 # change it
>>> dll.func(1)
7
我正在尝试将 C 主程序写入 dll,Python 将从该 dll 导入所有内容(包括所有变量和函数),并运行在 dll 中定义的函数。但是,我打算不仅将函数而且从 DLL 导出变量到 Python。 我了解如何使用 DLL 将函数公开给 Python,但我不确定如何使用 Python.
中的 Ctype 从 dll 访问变量举个例子: 如果在 header 中,我们有 #DEFINE MAXDEVNUMBER 4。 当我使用 ctype print mydll.MAXDENUMBER 它给我一个错误。函数 'MAXDENUM' 未找到
您无法访问预处理器宏,因为它们不是从 DLL 中导出的。您只能访问导出的 C 函数和全局变量。
例如,test.c:
__declspec(dllexport) int b = 5;
__declspec(dllexport) int func(int a)
{
return a + b;
}
>>> from ctypes import * >>> dll = CDLL('test') >>> dll.func(1) 6 >>> x=c_int.in_dll(dll,'b') # access the global variable >>> x.value 5 >>> x.value = 6 # change it >>> dll.func(1) 7