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

2019-06-14 09:11发布

问题:

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