最近再写 dll 为了通用性(c#可以调用) 输出函数肯定用pchar 作为参数 和 返回值了 这是毫无疑问的 查阅了些资料
http://blog.sina.com.cn/s/blog_4ff1251f0100dsu6.html
并且在其他地方下到一些代码 function StrPch(const stPas: string): PChar;
// Pascal -> PChar
// 直接使用 PChar 转化有时会转化出错
begin
GetMem(Result, Length(stPas) + 1);
StrPCopy(Result, stPas);
end;function GetSpellCode(szText: PChar; iMode, iCount: Integer): PChar;
// Call MakeSpellCode
begin
Result := StrPch(MakeSpellCode(String(szText), iMode, iCount)); //这里直接用pchar 有时会报错? 搞不懂
end;function GetAdminPath: ShortString; stdcall;
var
vPath: pchar
vSize: Integer;
begin vSize := MAX_PATH;
vPath := GetMemory(vSize);
ExpandEnvironmentStrings('%HOMEDRIVE%%HOMEPATH%', vPath, MAX_PATH);
//ShowMessage(StrPas(vPath));
Result := StrPas(vPath); end;
都用到了 内存分配函数 可没有释放 势必会造成内存泄露吧(CheckMem.pas检查有)
请问 dll 涉及输出函数中 string 标准写法 如何?
http://blog.sina.com.cn/s/blog_4ff1251f0100dsu6.html
并且在其他地方下到一些代码 function StrPch(const stPas: string): PChar;
// Pascal -> PChar
// 直接使用 PChar 转化有时会转化出错
begin
GetMem(Result, Length(stPas) + 1);
StrPCopy(Result, stPas);
end;function GetSpellCode(szText: PChar; iMode, iCount: Integer): PChar;
// Call MakeSpellCode
begin
Result := StrPch(MakeSpellCode(String(szText), iMode, iCount)); //这里直接用pchar 有时会报错? 搞不懂
end;function GetAdminPath: ShortString; stdcall;
var
vPath: pchar
vSize: Integer;
begin vSize := MAX_PATH;
vPath := GetMemory(vSize);
ExpandEnvironmentStrings('%HOMEDRIVE%%HOMEPATH%', vPath, MAX_PATH);
//ShowMessage(StrPas(vPath));
Result := StrPas(vPath); end;
都用到了 内存分配函数 可没有释放 势必会造成内存泄露吧(CheckMem.pas检查有)
请问 dll 涉及输出函数中 string 标准写法 如何?
问题3 :dll 返回 pchar 会有不稳定的情况 ?
procedure GetApplicationName(var Lp:String);StdCall;
begin
StrCopy(PChar(Lp),PChar(ChangeFileExt(ExtractFileName(Application.ExeName),'')));
end;
对于文件名 不可能超过 255 吧 所以你的没有问题 也可直接使用 shortstring
dll要给其他语言用,尽量只是用PAnsiChar吧。string毕竟是delphi自己的东西
// Pascal -> PChar
// 直接使用 PChar 转化有时会转化出错
begin
GetMem(Result, Length(stPas) + 1);
StrPCopy(Result, stPas);
end;
这个写成下面的样子就应该没有问题了
function StrPch(const stPas: string): PChar;
// Pascal -> PChar
// 直接使用 PChar 转化有时会转化出错
begin
GetMem(Result, Length(stPas) + 1);
//StrPCopy(Result, stPas);
CopyMemory(Result, stPas[1], Length(stPas));
Result[Length(stPas)] := #0;
end;
// Call MakeSpellCode
begin
Result := StrPch(MakeSpellCode(String(szText), iMode, iCount)); //这里直接用pchar 有时会报错? 搞不懂
end;
//试一试下面的方式?
function GetSpellCode(szText: PChar; iMode, iCount: Integer): PChar;
// Call MakeSpellCode
begin
Result := StrPch(MakeSpellCode(PChar(szText), iMode, iCount));
end;
//试
如果 dll 函数 返回值为pchar exe 里再访问该地址 大量访问会不会有异常 ?
就像上面提到的 直接 pchar('sss') 返回有事会出错。
http://blog.sina.com.cn/s/blog_4ff1251f0100dsu6.html
如 :function GetSysParamEx(ParamKey:PChar; const myResult: pchar):boolean;stdcall;
那么 当不知道 myResult 大小时 怎么分配内存
这里推荐 exe 管理内存 dll只负责 填充pchardll 内要使用 strcopy move等内存复制函数 而不要简单返回一个指针。