Delphi版本Delphi 10 Seattle
Delphi代码
unit Unit1; interface function testint(): integer; stdcall; function testpchar(): PChar; stdcall; implementation function testint(): integer; stdcall; begin result := 666; end; function testpchar(): PChar; stdcall; begin result := '中文'; end;
library Project1; { Important note about DLL memory management: ShareMem must be the first unit in your library's USES clause AND your project's (select Project-View Source) USES clause if your DLL exports any procedures or functions that pass strings as parameters or function results. This applies to all strings passed to and from your DLL--even those that are nested in records and classes. ShareMem is the interface unit to the BORLNDMM.DLL shared memory manager, which must be deployed along with your DLL. To avoid using BORLNDMM.DLL, pass string information using PChar or ShortString parameters. } uses System.SysUtils, System.Classes, Unit1 in 'Unit1.pas'; {$R *.res} exports testint, testpchar; begin end.
Python调用
import ctypes dll = ctypes.windll.LoadLibrary("Project1.dll") ri = dll.testint() print(ri) rc = dll.testpchar() rc = ctypes.c_wchar_p(rc) print(rc.value)
备注:
ctypes定义了一系列基本C数据类型:
ctypes类型 |
C类型 |
Python类型 |
c_char |
char |
1个字符的字符串 |
c_wchar |
wchar_t |
1个字符的unicode字符串 |
c_byte |
char |
int/long |
c_ubyte |
unsigned char |
int/long |
c_short |
short |
int/long |
c_ushort |
unsigned short |
int/long |
c_int |
int |
int/long |
c_uint |
unsigned int |
int/long |
c_long |
long |
int/long |
c_ulong |
unsigned long |
int/long |
c_longlong |
__int64 或 long long |
int/long |
c_ulonglong |
unsigned __int64 或 unsigned long long |
int/long |
c_float |
float |
float |
c_double |
double |
float |
c_char_p |
char * (NUL结尾字符串) |
string或None |
c_wchar_p |
wchar_t * (NUL结尾字符串) |
unicode或None |
c_void_p |
void * |
int/long或None |