在C++本地类中添加托管类的变量

使用gcroot可以实现在C++本地类中添加托管类变量.例子:

#include<vcclr.h>  //必须包含

using namespace System;
using namespace System::Collections::Generic;
using namespace System::Text;
using namespace System::IO::Ports;
using namespace System::Threading;
using namespace System::Runtime::InteropServices;

class test{
public:
   test(){port = gcnew gcroot<SerialPort^>;}
   //在gc堆中分配托管类变量SerialPort^ port.应该是,否则的话就是gcroot中的一指针指向托管类成员port
   void MarshalString(String^ s, string &os);//String^ --> string
   void ToString(string os, String^ &s);//string --> String^
private:
   gcroot<SerialPort^> port;
   String^ str1;
   string str2;
}

void test::MarshalString( String ^ s, string& os ) {
   using namespace Runtime::InteropServices;
   const char* chars =
      (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
   os = chars;
   Marshal::FreeHGlobal(IntPtr((void*)chars));
}

void test::ToString(string os, String^ &s)
{
    s = gcnew String(os.c_str());
}


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/zonian/archive/2008/08/07/2782761.aspx 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值