如何将 PChar 从 DLL 函数返回到 VB6 应用程序,而不会有崩溃或内存泄漏的风险? [英] How can I return a PChar from a DLL function to a VB6 application without risking crashes or memory leaks?

查看:9
本文介绍了如何将 PChar 从 DLL 函数返回到 VB6 应用程序,而不会有崩溃或内存泄漏的风险?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个供 VB6 应用程序使用的 DLL.这个 DLL 必须提供几个函数,其中一些函数必须返回字符串.

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.

这是 VB6 声明:

Declare Function MyProc Lib "mylib.dll" (ByVal Param As String) As String

这是 mylib.dll 中的 Delphi 实现存根:

And this the Delphi implementation stub in mylib.dll:

function MyProc(AParam: PChar): PChar; stdcall;
var
  ReturnValue: string;
begin
  ReturnValue := GetReturnValue(AParam);
  Result := ???;
end;

我必须在这里返回什么?谁来释放返回的 PChar 字符串的内存?

What do I have to return here? Who will free the memory of the returnd PChar string?

我问的是 Delphi 2005 (PChar = PAnsiChar)

I'm asking about Delphi 2005 (PChar = PAnsiChar)

推荐答案

你需要制作一个 BSTR.VB6 字符串实际上是 BSTR.在Delphi端调用SysAllocString(),将BSTR返回给VB6端.VB6 端将不得不调用 SysFreeString() 来释放字符串 - 它会自动完成.

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.

如果 PChar 对应于 ANSI 字符串(您的情况),您必须手动将其转换为 Unicode - 为此使用 MultiByteToWideChar().请参阅 此答案了解如何更好地使用 SysAllocStringLen()MultiByteToWideChar() 一起.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆