开发者

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

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 getIn开发者_StackOverflowfo(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.


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)


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜