如何将 char * 转换为 BSTR? [英] How to convert char * to BSTR?

查看:23
本文介绍了如何将 char * 转换为 BSTR?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 char * 从 C dll 传递到 VB

How can I pass a char * from C dll to VB

这里是示例代码:

void Cfunc(char *buffer,int len)
{
  BSTR buf_bstr = SysAllocString((BSTR)buffer);
  VBptr.VBfunc(buf_bstr,len);
}

这个功能不起作用,实际上一些其他值被发送到VB而不是实际值.

This function is not working, In actual some other values are sent to the VB rather than the actual value.

有人可以提出解决方案吗?

Could anyone please suggest a solution?

推荐答案

调用 MultiByteToWideChar(),然后调用 SysAllocString()SysAllocStringLen()代码>.

Call MultiByteToWideChar(), then either SysAllocString() or SysAllocStringLen().

当您不再需要 BSTR 时,不要忘记调用 SysFreeString().

Don't forget to call SysFreeString() when you no longer need the BSTR.

详细说明(SysAllocStringLen() 变体——它更短更快):

In detail (SysAllocStringLen() variant – it's shorter and faster):

  1. 调用 MultiByteToWideChar() 并传递 0 作为第五个和第六个参数.它将返回与 ANSI 字符串等效的 Unicode 字符数.请记住,ANSI 字符串可以包含任何字符,而不仅仅是 ASCII,因此在给定 ANSI 字符串长度的情况下手动计算 Unicode 字符数的任何尝试可能在某些情况下有效,而在其他情况下无效.

  1. Call MultiByteToWideChar() and pass 0 as fifth and sixth parameters. It will return the number of characters in the Unicode equivalent of the ANSI string. Remember, ANSI string can contain whatever characters, not only ASCII, so any attempts to manually calculate the number of Unicode characters given the ANSI string length may work in some cases and not work in others.

使用 SysAllocStringLen() 为 BSTR 分配一个缓冲区.传递 0 作为第一个参数,Unicode 字符的数量作为第二个参数.您现在有一个正确分配但未初始化的 BSTR.它已经有尾随零的位置,并且该尾随零已正确放置.

Allocate a buffer for the BSTR with SysAllocStringLen(). Pass 0 as the first parameter and the number of Unicode characters as the second parameter. You now have a properly allocated but uninitialized BSTR. It already has place for the trailing zero and this trailing zero is properly placed.

第二次调用MultiByteToWideChar(),这一次通过那里分配的BSTR.该函数会将字符串转换为 Unicode 并将结果复制到 BSTR.现在您有了一个正确分配的 BSTR,其中包含您的 ANSI 字符串的 Unicode 等价物.

Call MultiByteToWideChar() second time and this time pass the allocated BSTR there. The function will convert the string into Unicode and copy the result into the BSTR. Now you have a propely allocated BSTR containing the Unicode equivalent of your ANSI string.

将 BSTR 传递给 VB.享受吧.

Pass the BSTR into VB. Enjoy.

调用 SysFreeString() 释放 BSTR.

Call SysFreeString() to deallocate the BSTR.

这篇关于如何将 char * 转换为 BSTR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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