C++调用C#库用到的几个类型转换:C++string转换成C#的String,C++string转C#的byte

Program为C#dll中定义的类,需要调用它里面的接口

Program^ c = gcnew Program();

1.C++string转换成C#的String

string recv_buf2;
String^ inifile = gcnew String(recv_buf2.c_str());
c->open_camera(inifile);

2.C++string转C#的byte

string recv_devaddr="0x18";
BYTE devaddr;
bool result1 = str2byte(recv_devaddr, devaddr);
c->read_register(devaddr,str1, read_mode);  //最后传入的就是byte类型的0x18

str2byte函数是借鉴另外的博文

bool str2byte(const std::string& str, BYTE& bRet)
{
	   bRet = 0x00;       //结果
	   size_t iPos = 1;   //位
	   size_t power = 1;  //幂次
	
		   //没找的‘x‘返回
		   if (std::string::npos == str.find("x"))
		   {
		     return false;
		   }
	
		   //从右往左依次取每个字符
		   while (str.find("x") != (str.length() - iPos))
		   {
		     char cVal = str[str.length() - iPos];
		     int iVal = int(cVal);
		
		     //0~9
			     if ((iVal >= 48) && (iVal <= 57))
			     {
			       bRet += ((iVal - 48) * power);
			     }
		     //A~F
			     else if ((iVal >= 65) && (iVal <= 70))
			     {
			       bRet += ((iVal - 55) * power);
			     }
		     //a~f
			    else if ((iVal >= 97) && (iVal <= 102))
			     {
			       bRet += ((iVal - 87) * power);
			     }
		
			     ++iPos;
		     power *= 16;
		   }
	
		  return true;
	}

你可能感兴趣的:(c++,c#)