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