使用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