COM/ATL-无法封送LPSTR [英] COM/ATL - Unable to marshal LPSTR

查看:87
本文介绍了COM/ATL-无法封送LPSTR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在使用C ++编写一个库,并希望使其可移植并且可以使用其他语言(如.NET语言)进行访问.这就是为什么我决定使用ATL将库包装到COM DLL中的原因.
现在我的问题是我无法将ANSI字符串从库通过RCW传递回客户端.我的代码如下所示:

 //  IDL:
[propet,帮助字符串("  )] HRESULT String([out, retval ] LPSTR * plpszValue);

// 方法的实现:
STDMETHODIMP CMyClass :: get_String(LPSTR * plpszValue)
{
std :: string sStdStr(" ); // 创建标准字符串
* plpszValue = _strdup(sStdStr.c_str()); // 复制标准字符串,并将指向副本的指针传递回调用方.

返回S_OK;
} 

现在,访问代码如下所示:

 //  C#代码
MyClass oClass =  MyClass();
Console.WriteLine(oClass.字符串); // 引发System.Interop.COMException  

但是将字符串传递到另一个方向(客户端- >服务器,则表示propput)工作正常.同样,返回空或预定义的字符串也不会引发异常:

 // 方法:
STDMETHODIMP CMyClass :: get_String(LPSTR * plpszValue)
{
    std :: string sStdStr(" ); // 创建标准字符串
    * plpszValue = " ;

    返回 S_OK;
} 

这就是为什么我认为问题与_strdup()有关.谁能告诉我我做错了什么?我为字符串分配内存并将其指针返回给客户端的想法有什么问题?

希望您能提供帮助,谢谢!

附注:我的项目是使用多字节字符集(ANSI)而不是Unicode构建的.由SysAllocString分配并由SysFreeString释放.
问候.


Hi everyone,

I am writing a library using C++ and want to make it portable and accessable in other languages (like .NET languages). This is why I decided to wrap the library inside an COM DLL, using ATL.

Now my problem is that I am unable to pass ANSI strings from the library through the RCW back to the client. My code looks something like this:

// IDL:
[propget, helpstring("String")] HRESULT String([out, retval] LPSTR* plpszValue);

// Implementation of the method:
STDMETHODIMP CMyClass::get_String(LPSTR* plpszValue)
{
	std::string sStdStr("Test");	// Create std string
	*plpszValue = _strdup(sStdStr.c_str());	// Copy std string and pass pointer to the copy back to the caller.

	return S_OK;
}

Now accessing the code looks like this:

// C# code
MyClass oClass = new MyClass();
Console.WriteLine(oClass.String);	// Throws System.Interop.COMException

However passing strings into the other direction (client -> server, means propput) works fine. Also returning an empty or predefined string does not throw an exception:

// Implementation of the method:
STDMETHODIMP CMyClass::get_String(LPSTR* plpszValue)
{
    std::string sStdStr("Test");    // Create std string
    *plpszValue = "Test";

    return S_OK;
}

This is why I think the problem is related into _strdup(). So can anyone tell me what I did wrong? What''s wrong with my idea of allocating memory for a string and returning it''s pointer to the client?

I hope you can help, thank you!

P.S.: My project is built with Multi-Byte-Characterset (ANSI), not Unicode.

解决方案

Usually COM is using BSTR for marshalled strings. Allocated by SysAllocString and freed by SysFreeString.
Regards.


这篇关于COM/ATL-无法封送LPSTR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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