将BSTR从C ++ DLL函数传递到VB6应用程序 [英] Pass BSTR from C++ DLL function to VB6 application

查看:187
本文介绍了将BSTR从C ++ DLL函数传递到VB6应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的VB6应用程序中包含以下代码:

I have this code in my VB6 app:

Private Declare Function FileGetParentFolder Lib "Z-FileIO.dll" _
(ByVal path As String) As String

Output.AddItem FileGetParentFolder(FileText.Text)

输出是一个列表,FileText是包含文件路径的文本字段。我的C ++ DLL包含以下功能:

Output is a list, FileText is a text field containing a file path. My C++ DLL contains this function:

extern "C" BSTR ZFILEIO_API FileGetParentFolder(Path p)
{
    try {
        return SysAllocString(boost::filesystem::path(p).parent_path().c_str());
    } catch (...) {
        return SysAllocString(L"");
    }
}

其中 Path 的类型定义为 LPCSTR 。该参数完美地进入了我的DLL,但是无论我尝试回传什么,VB6应用程序仅显示垃圾内容。我用 SysAllocStringByteLength 尝试了几种不同的方法,将 SysAllocString 参数转换为 LPCWSTR 和其他变体。要么,我只看到字符串的第一个字母,要么我只看到带点的Y,而不是真正的字符串。有谁知道创建有效的BSTR并将其从C ++传递到VB6的真正方法是什么?

where Path is typedef'd as LPCSTR. The argument comes into my DLL perfectly, but whatever I try to pass back, the VB6 app shows only garbage. I tried several different methods with SysAllocStringByteLength, casting the SysAllocString argument to LPCWSTR and other variants. Either, I only see the first letter of the string, or I see only Y's with dots, just not the real string. Does anyone know what the real method is for creating and passing valid BSTRs from C++ to VB6?

推荐答案

希望这会指向您正确的方向。从内存中...

Hopefully this will point you in the right direction. From memory...

VB6在内部使用COM BSTR(2字节宽的字符串),但是在与外部DLL通信时,它使用单字节或多字节字符串。 (可能是UTF-8,但我不太确定。)LPCSTR的Path typedef是一个ANSI字符串,这就是为什么您可以正确接收它的原因。您生成的返回值是一个宽字符字符串,但是VB需要一个ANSI字符串。在返回它之前,需要使用WideCharToMultiByte来转换您的返回值。

VB6 uses COM BSTRs (2-byte wide character strings) internally, but when communicating with external DLLs it uses single- or multi-byte strings. (Probably UTF-8, but I don't remember for sure.) Your Path typedef to LPCSTR is an ANSI string, and that's why you can receive it correctly. The return value you generate is a wide-character string, but VB is expecting an ANSI string. You'll need to use WideCharToMultiByte to convert your return value before returning it.

VB进行这种隐式转换似乎有点奇怪,但这就是事实。 (据我记得。)

Seems a little odd that VB does this implicit conversion, but that's the way it is. (As far as I remember.)

这篇关于将BSTR从C ++ DLL函数传递到VB6应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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