如何从本地返回的文本(C ++)code [英] How to return text from Native (C++) code

查看:89
本文介绍了如何从本地返回的文本(C ++)code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的PInvoke为母语之间的互操作性(C ++)code和管理(C#)code。我想实现的就是从本地code一些文​​本到我的管理code。为了这个,我尝试很多很多的事情,例如由裁判通过串/ StringBuilder的,使用[IN]和[OUT],封送处理至LPSTR,从功能等返回的字符串,但没有我的情况下工作。与一些小code任何帮助将是非常美联社preciated。

I am using Pinvoke for Interoperability between Native(C++) code and Managed(C#) code. What i want to achieve is get some text from native code into my managed code. For this i try lot lot of things,e.g passing string/stringbuilder by ref, using [IN] and [OUT], Marshaling to LPSTR, returning string from function etc. but nothing works in my case. Any help with some small code would be highly appreciated.

推荐答案

我会用它做一个 BSTR ,因为这意味着你不必调用本机两次每串,一旦得到的长度,然后一次得到的内容。

I'd do it with a BSTR since it means you don't have to call into native twice per string, once to get the length and then once to get the contents.

随着 BSTR 编组会照顾取消分配的 BSTR 与正确的内存管理器,所以你可以放心地它传递出你的C ++ code的。

With a BSTR the marshaller will take care of deallocating the BSTR with the right memory manager so you can safely pass it out of your C++ code.

C ++

#include <comutil.h>
BSTR GetSomeText()
{
    return ::SysAllocString(L"Greetings from the native world!");
}

C#

[DllImport(@"test.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.BStr)]
private static extern string GetSomeText();

有一个小缺点的 BSTR ,即它带有UTF-16有效载荷,但源数据可能是的char *

There is one minor drawback of the BSTR, namely that it carries a UTF-16 payload but your source data may well be char*.

要克服这一点,你可以从的char * 转换包到 BSTR 是这样的:

To overcome this you can wrap up the conversion from char* to BSTR like this:

BSTR ANSItoBSTR(const char* input)
{
    BSTR result = NULL;
    int lenA = lstrlenA(input);
    int lenW = ::MultiByteToWideChar(CP_ACP, 0, input, lenA, NULL, 0);
    if (lenW > 0)
    {
        result = ::SysAllocStringLen(0, lenW);
        ::MultiByteToWideChar(CP_ACP, 0, input, lenA, result, lenW);
    } 
    return result;
}

这是最难的一出的方式,现在可以很容易地从 LPWSTR BSTR C>,的std ::字符串的std :: wstring的等。

That's the hardest one out of the way, and now it's easy to add other wrappers to convert to BSTR from LPWSTR, std::string, std::wstring etc.

这篇关于如何从本地返回的文本(C ++)code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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