如何将PChar从DLL函数返回到VB6应用程序,而不会有崩溃或内存泄漏的风险? [英] How can I return a PChar from a DLL function to a VB6 application without risking crashes or memory leaks?
问题描述
这是VB6声明:
声明函数MyProc Libmylib.dll(ByVal Param As String)As String
这个Delphi实现存根在 mylib.dll
:
函数MyProc(AParam:PChar):PChar;标准
var
ReturnValue:string;
begin
ReturnValue:= GetReturnValue(AParam);
结果:= ???
结束
我必须返回这里?谁将释放回归PChar字符串的记忆?
编辑:我在问Delphi 2005( PChar
= PAnsiChar
)
制作BSTR。 VB6字符串实际上是BSTR。在Delphi端调用SysAllocString(),并将BSTR返回到VB6端。 VB6端将不得不调用SysFreeString()来释放字符串 - 它将自动执行。
如果PChar对应于ANSI字符串(您的情况),则必须手动将其转换为Unicode - 使用MultiByteToWideChar()。请参阅此答案,了解如何更好地使用SysAllocStringLen()和MultiByteToWideChar()在一起。
I have to create a DLL which is used by a VB6 application. This DLL has to provide several functions, some of them must return strings.
This is the VB6 declaration:
Declare Function MyProc Lib "mylib.dll" (ByVal Param As String) As String
And this the Delphi implementation stub in mylib.dll
:
function MyProc(AParam: PChar): PChar; stdcall;
var
ReturnValue: string;
begin
ReturnValue := GetReturnValue(AParam);
Result := ???;
end;
What do I have to return here? Who will free the memory of the returnd PChar string?
EDIT: I'm asking about Delphi 2005 (PChar
= PAnsiChar
)
You need to craft a BSTR instead. VB6 strings are actually BSTRs. Call SysAllocString() on the Delphi side and return the BSTR to the VB6 side. The VB6 side will have to call SysFreeString() to free the string - it will do it automatically.
If PChar corresponds to an ANSI string (your case) you have to manually convert it to Unicode - use MultiByteToWideChar() for that. See this answer for how to better use SysAllocStringLen() and MultiByteToWideChar() together.
这篇关于如何将PChar从DLL函数返回到VB6应用程序,而不会有崩溃或内存泄漏的风险?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!