How to use COM to pass a string from c# to c++?

混江龙づ霸主 提交于 2019-12-08 09:12:07

问题


when i try to call c# code from c++, i followed instructions from this article

http://support.microsoft.com/kb/828736

part of my c# is :

[Guid("6A2E9B00-C435-48f8-AEF1-747E9F39E77A")]
public interface IGameHelper
{
 void getInfo(out string result);
}

public class GameHelper : IGameHelper
{
 void getInfo(out string result)
 {
  result =  new StringBuilder().Append("Hello").ToString();
 }

}

part of my c++ code:

#import "../lst/bin/Release/LST.tlb" named_guids raw_interfaces_only
using namespace LST;
using namespace std;

...
HRESULT hr = CoInitialize(NULL);
IGameHelperPtr pIGame(__uuidof(GameHelper));
BSTR ha = SysAllocString(NULL);
pIGame->GetInfo(&ha);
wprintf(_T(" %s"),ha);
SysFreeString(ha);

but I just cannot get the string result value, it works fine when i try to get integer results,but not string.

I dont know COM very much. PLEASE HELP ME. Thank you.


回答1:


According to Msdn if you call SysAllocString whilst passing in NULL, it returns NULL.

Aren't you therefore passing a reference to a NULL pointer into your COM interface? And if so ha will never get populated? (I'm not sure with COM so may be wrong)




回答2:


Generally your code should work but first make sure it compiles correctly as void getInfo(out string result) inside of GameHelper should be public. Then again pIGame->GetInfo(&ha); should be fixed with getInfo. So you may be running an older version of the code.




回答3:


Change your C# code to:

[Guid("6A2E9B00-C435-48f8-AEF1-747E9F39E77A")]
public interface IGameHelper
{
    string getInfo();
}


public class GameHelper : IGameHelper
{
    public string getInfo()
    {
       return "Hello World";
    }

}

Then your C++ client to:

HRESULT hr = CoInitialize(NULL);
IGameHelperPtr pIGame(__uuidof(GameHelper));
_bstr_t ha = pIGame->GetInfo();
wprintf(_T(" %s"),ha);

That should work



来源:https://stackoverflow.com/questions/6262326/how-to-use-com-to-pass-a-string-from-c-sharp-to-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!