来自C ++ COM的C#字符串 [英] String for C# from C++ COM

查看:80
本文介绍了来自C ++ COM的C#字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++ DLL,并且某些函数返回以NULL结尾的Unicode字符串:

I have a C++ DLL and some functions return Unicode null-terminated strings:

void SomeFunc(wchar_t* StrBuf)

调用方必须分配StrBuf-字符串最多可以包含256个字符。
此DLL还公开了一个COM对象以通过COM通过C#使用此DLL。 IDL中的定义:

The caller must allocate StrBuf - string can be up to 256 characters. This DLL also exposes a COM object to use this DLL from C# via COM. Definition in IDL:

[id(1), helpstring("bla")]
HRESULT SomeFunc([in,out] BSTR* TextStr, [out,retval] LONG* RetValue);

当前C#代码如下:

string val = new string('\0', 256); // Allocate memory
MyComObj.SomeFunc(ref val); // Get string
val = val.Substring(0, val.IndexOf('\0')); // Convert from null-terminated string

转换

是否有一种方法可以定义这样的COM函数,因此它可以从C#使用起来更容易?现在,它看起来很丑陋,需要三行调用该函数,如果一个函数有两个字符串参数,则需要五行。

Is there a way to define such a COM function so it can be used from C# easier? Right now it looks ugly and takes three lines to call the function or five lines if a function has two string parameters.

推荐答案

已解决。在C ++中,我在COM包装程序中使用以下代码:

Solved. In C++ I use this code in the COM wrapper:

STDMETHODIMP MyClassClass::SomeFunc(BSTR* OptionValue, LONG* RetValue)
{
    *RetValue = 0;
    UNICODECHAR txt[MAXSTATSTRLEN];

    //... Copy text to txt variable
    *OptionValue = W2BSTR(txt);
    return S_OK;
}

IDL:

[id(1), helpstring("")] HRESULT SomeFunc([out] BSTR* OptionValue, [out,retval] LONG* RetValue);

在C#中,现在可以轻松地调用它:

In C# it can now be called easily:

string val;
MyComObj.SomeFunc(out val);

这篇关于来自C ++ COM的C#字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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