gcc
似乎默认导出函数,您可以使用任何 PE 查看器,如 PE Explorer (View > Export) 来查看导出的函数:
但是,如果你尝试用 VC++ 编译这段代码,它不会为你导出这个函数,你会看到没有导出函数:
您需要要求它导出此功能:
__declspec(dllexport) int addition(int a, int b){
return a+b;
}
至于调用约定,规则很简单:
如果您的函数使用__stdcall
,就像大多数 Win32API 一样,您需要使用WinDLL('mylib.dll')
or导入 DLL windll.mylib
,例如:
> type mylib.c
__declspec(dllexport) int __stdcall addition(int a, int b) {
return a+b;
}
***********************************************************************
> cl mylib.c /link /dll /out:mylib.dll
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
mylib.c
Microsoft (R) Incremental Linker Version 8.00.50727.762
Copyright (C) Microsoft Corporation. All rights reserved.
/out:mylib.exe
/dll
/out:mylib.dll
mylib.obj
Creating library mylib.lib and object mylib.exp
***********************************************************************
> python
>>> from ctypes import *
>>>
>>> WinDLL('mylib.dll').addition(1, 2)
3
>>> windll.mylib.addition(1, 2)
3
>>>
如果您的函数使用__cdecl
,witch 是默认调用约定,您需要使用CDLL('mylib.dll')
or导入 DLL cdll.mylib'
,例如:
> type mylib.c
// `__cdecl` is not needed, since it's the default calling convention
__declspec(dllexport) int addition(int a, int b){
return a+b;
}
***********************************************************************
> cl mylib.c /link /dll /out:mylib.dll
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
mylib.c
Microsoft (R) Incremental Linker Version 8.00.50727.762
Copyright (C) Microsoft Corporation. All rights reserved.
/out:mylib.exe
/dll
/out:mylib.dll
mylib.obj
Creating library mylib.lib and object mylib.exp
***********************************************************************
> python
>>> from ctypes import *
>>>
>>> CDLL('mylib.dll').addition(1, 2)
3
>>> cdll.mylib.addition(1, 2)
3
>>>