delphi调用python文件_Python 如何调用Delphi动态联接库

本文详细介绍了如何使用Python的ctypes模块调用由C或Delphi编译的动态链接库(DLL),包括传递基本数据类型、指针类型以及字符串的方法,并通过一个Delphi编写的DLL实例展示了具体的应用过程。
摘要由CSDN通过智能技术生成

python 从 2.5 开始支持 调用动态联接库中的函数,我们可以用C或delphi 为其开发动态联接库。

我们以 stdcall 调用格式的函数为例说明

-------------------------------------------------------

1 基本数据类型

python的c_types C delphi

c_int int integer

c_double double double

2 指针类型

byref(

c_int

) int

* pinteger

byref( c_double

) double

* pdouble

byref(

c_char_array_1024) char

* pchar

---------------------------------------------------------

3 Delphi 写的动态联接库

---------------------------------------------------------

library PTEST1;

uses

SysUtils,

windows,

Classes;

{$R *.res}

//测试两个整数的加法

function test( a,b:integer)

:integer; stdcall;

begin

result:=a+b;

end;

// 传入一个实数 b , 用 a 是 double型的指针

// 用 a^ 将double 类型的 值传回

procedure testD(b:double;

a:pdouble); stdcall;

begin

a^

:=1234.56*b;

end;

// 回传字符串

function teststr( pstr:pchar; N:integer)

:integer; stdcall;

const s:string='你好,张三先生abcd1234';

var k:integer;

begin

k:=length(s)+1;

if

k>N then k:=N;

system.Move(s[1], pstr^,k );

result:= k

;

end;

exports test,testD,teststr

;

begin

end.

-------------------------------------------------

python 3.1

#coding=gbk

import ctypes

from ctypes import *

MY_DLLNAME = "c:\\wxt\\dll\\PTEST1.dll"

MY_DLL =

windll.LoadLibrary( MY_DLLNAME )

#测试传入整数,返回整数

def test( a, b):

fun = MY_DLL.test

return fun( a,b)

#测试传入实数,传出实数

def testd( b ):

fun = MY_DLL.testD

bb = c_double(b)

a = c_double()

fun ( bb, byref( a)

) return a.value

#测试传出字符串

def teststr( ):

fun = MY_DLL.teststr

s = create_string_buffer("\x00"*1024)

fun( byref(s),1024)

s1 = s.value.decode( "gbk")

return s1

print( test( 1,2))

print( testd( 2.0))

print ( teststr())

运行结果:

3

2469.12

你好,张三先生abcd1234

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值