Csharp/C#教程:如何使用COM将字符串从c#传递给c ++?分享


如何使用COM将字符串从c#传递给c ++?

当我尝试从c ++调用c#代码时,我按照本文的说明操作

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

我的c#的一部分是:

[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(); } } 

我的c ++代码的一部分:

 #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); 

但我只是无法得到字符串结果值,当我尝试获取整数结果时,它工作正常,但不是字符串。

我不太了解COM。 请帮我。 谢谢。

根据 Msdn,如果在传入NULL时调用SysAllocString,则返回NULL。

您是否因此将对NULL指针的引用传递到COM接口? 如果是这样,哈哈将永远不会被填充? (我不确定COM可能是错的)

通常你的代码应该工作,但首先要确保它正确编译,因为void getInfo(out string result)中的void getInfo(out string result)应该是公共的。 然后再次pIGame->GetInfo(&ha); 应该用getInfo 。 因此,您可能正在运行旧版本的代码。

将您的C#代码更改为:

 [Guid("6A2E9B00-C435-48f8-AEF1-747E9F39E77A")] public interface IGameHelper { string getInfo(); } public class GameHelper : IGameHelper { public string getInfo() { return "Hello World"; } } 

然后你的C ++客户端:

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

这应该工作

上述就是C#学习教程:如何使用COM将字符串从c#传递给c ++?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/988614.html

(0)
上一篇 2021年12月24日
下一篇 2021年12月24日

精彩推荐