在Python脚本中从Delphi DLL获取PChar参数
假设我在DLL中有这个函数在Python脚本中从Delphi DLL获取PChar参数,python,delphi,dll,pchar,Python,Delphi,Dll,Pchar,假设我在DLL中有这个函数 function test_3(sInput, sOutput : PChar; sSize : int64): Integer; stdcall; var sTmp : string; fText : TextFile; begin sTmp := '+++ ' + sInput + ' +++'; StrPLCopy(sOutput, PChar(sTmp), sSize); Result := 69; AssignFile(fText,
function test_3(sInput, sOutput : PChar; sSize : int64): Integer; stdcall;
var
sTmp : string;
fText : TextFile;
begin
sTmp := '+++ ' + sInput + ' +++';
StrPLCopy(sOutput, PChar(sTmp), sSize);
Result := 69;
AssignFile(fText, 'test.txt');
Rewrite(fText);
Writeln(fText, 'in: ' + sInput);
Writeln(fText, 'out: ' + sOutput);
CloseFile(fText);
end;
在我的Delphi程序中,我这样称呼它
…
Input := EdtIn.Text;
OutputSize := Input.Length + 8;
Output := AllocMem(OutputSize);
RC := test_3(PChar(Input), Output, OutputSize);
EdtOut.Text := Output;
FreeMem(Output);
而且它工作得很好。现在我想从Python脚本中调用该函数
import ctypes as ct
...
myString = "test Delphi 10.3 DLL"
outputsize = len(myString) + 8
…
test_3 = lib.test_3
test_3.restype = ct.c_int
test_3.argtypes = [ct.c_wchar_p, ct.c_wchar_p]
sOutput = ct.create_string_buffer(outputsize)
print("sOutput = " + sOutput.value)
我得到一个错误
ctypes.ArgumentError:参数2::错误类型
所以我的问题是:Delphi中AllocMem的Python等价物是什么。
我必须明确指出,当然,所有代码都是示例,在现实生活中,我无法访问DLL中的Delphi代码。下面是一个简单完整的示例,演示如何执行此操作: 德尔福图书馆 索乌图书馆60391682; 使用 SysUtils; 函数testStringOutput,输出:PChar;OutputLen:Int64:Integer;stdcall; 变量 tmp:字符串; 开始 tmp:='++'+输入+'++'; StrPLCopyOutput,PChartmp,OutputLen-1; //-1,因为StrPLCopy处理空终止符 结果:=0; 终止 出口 testStringOut; 开始 终止 调用Delphi库的Python程序 导入ctypes lib=ctypes.windlr'SO_60391682.dll' testStringOut=lib.testStringOut testStringOut.restype=ctypes.c_int testStringOut.argtypes=ctypes.c_wchar_p,ctypes.c_wchar_p,ctypes.c_int64 输出=ctypes.create\u unicode\u buffer256 res=testStringOut'foo',output,lenoutput 打印'res={},output={}'。格式文件,output.value
尝试使用ct.c_char_p作为argtype.Unicode Delphi或ANSI Delphi?Python2还是Python3?对不起,我忘了指出:Delphi 10.3和Python3.7由于您使用的是Unicode Delphi版本,您对OutputSize的计算(至少在Delphi示例中是这样)无法判断Python是否错误。AllocMem以字节为单位分配内存,而不是以字符为单位。因此需要将OutputSize的值加倍,因为Unicode字符有两个字节大,并且输入和输出是ANSI字符串。不是真的。因为您使用的是Delphi 10.3,所以PChar是PWideChar的别名,指向以null结尾的UTF-16字符元素数组的指针。是的,你的内存分配被破坏了。我很想回答这个问题,但在问题解决之前我不会这么做。是的,你救了我。我错过了创建unicode缓冲区。非常感谢你。