python calls Delphi to write Dll code samples
- 2020-06-15 09:20:43
- OfStack
First, take a look at the basic structure of the Delphi unit file:
unit Unit1; // Unit file name
interface // This is the interface keyword that identifies the unit file that the file calls
uses // A common unit used by a program
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs;
type // The components used by the program are defined here, 1 The classes, and the procedures and events corresponding to the components
TForm1 = class(TForm)
private // Define private variables and private procedures
{ Private declarations }
public // Define common variables and common procedures
{ Public declarations }
end;
var // Defines the public variables used by the program
Form1: TForm1;
implementation // Program code implementation part
{$R *.dfm}
end.
The Delphi unit is as follows (output ES6en.dll) :
unit hellofun;
interface
function getint():integer;stdcall;
function sayhello(var sname:PAnsiChar):PAnsiChar;stdcall;
implementation
function getint():integer;stdcall;
begin
result:=888;
end;
function sayhello(var sname:PAnsiChar):PAnsiChar;stdcall;
begin
sname:='ok!';
result:='hello,garfield !';
end;
end.
library hello;
{ 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,
hellofun in 'hellofun.pas';
{$R *.res}
exports
getint,
sayhello;
begin
end.
The call in python is as follows:
import ctypes
def main():
dll=ctypes.windll.LoadLibrary("hello.dll")
ri=dll.getint()
print(ri)
s=ctypes.c_char_p()
rs=ctypes.c_char_p()
rs=dll.sayhello(ctypes.byref(s))
print(s)
print(ctypes.c_char_p(rs))
if __name__ == '__main__':
main()
Run Python and the output is as follows:
>>>
888
c_char_p(b'ok!')
c_char_p(b'hello,garfield !')
>>>
Well, we can have python do some of the work in Delphi, or we can have Delphi do some of the work in Python.
The above procedure has been debugged in DelphiXE2 and Python3.2.
conclusion
That's the end of the Dll code example for python calling Delphi, and I hope you found it helpful. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!