c和c++混合编程中的字符串处理

string handling in c and C++ mix programming

本文关键字:字符串 处理 编程 c++ 混合      更新时间:2023-10-16

我想使用库中的API。我对它的第二个参数感到困惑。

    cs_disasm(handle,(const uint8_t*)("xffx43x12xd1"),4 , 0x0, 1, &insn);

上面的代码运行良好。"xffx43x12xd1",这个字符串表示一个机器码。我希望这个API能够接受任意机器码。我现在得到的是

uint32_t machine_code. I use it as follow, but not work.
std::stringstream ss;
ss<< std::hex  << setfill('0') << setw(2) <<  (int)(machine_code&0xff); // int decimal_value
std::string res1 ( ss.str() );
ss.str(std::string());
//cout << res1 << endl;
ss<< std::hex << setfill('0') << setw(2) << (int)((machine_code>>8)&0xff); // int decimal_value
std::string res2 ( ss.str() );
ss.str(std::string());

ss<< std::hex << setfill('0') << setw(2)  << (int)((machine_code>>16)&0xff); // int decimal_value
std::string res3 ( ss.str() );
ss.str(std::string());
ss<< std::hex << setfill('0') << setw(2) << (int)((machine_code>>24)&0xff); // int decimal_value
std::string res4 ( ss.str() );
string modified_machine_code = "\x"+ res1 +"\x"+  res2 +"\x"+ res3 +"\x"+ res4;
cs_disasm(hao_handle,(const uint8_t*)(modified_machine_code.c_str()),4 , 0x0, 1, &hao_insn);

我的代码有什么问题?如果你有更好的解决方案,那也很好。

你的字符串欺骗了你:"xffx43x12xd1"只有4个字符(好吧,加上结尾的NUL,但你不需要)你似乎认为它有16个字符,所有的x等,但这只是原始字节写入字符串文字的方式。

你真正想要的是一个字节数组,但由于在c++中字符串字面量是char的数组和char是一个字节,因此你的困惑。

您的原始字符串可以这样写得更清楚:

uint8_t code[] = { 0xff, 0x43, 0x12, 0xd1 };

现在,回答问题。你有一个int32_t,你想把它转换成一个int8_t数组。这可以通过三种方式实现:小端、大端或本机端(这将等于另一种方式,但哪一种取决于体系结构)。你想使用哪一个将取决于你从哪里得到的int32_t

对于本地端很简单,可以强制转换指针:

const uint8_t *code = reinterpret_cast<const uint8_t *>(&machine_code);

对于小端和大端,您最好构建一个新的数组:

const uint8_t code_le[] = {
    machine_code & 0xFF,
    (machine_code >> 8) & 0xFF,
    (machine_code >> 16) & 0xFF,
    (machine_code >> 24) & 0xFF,
};
const uint8_t code_be[] = {
    (machine_code >> 24) & 0xFF,
    (machine_code >> 16) & 0xFF,
    (machine_code >> 8) & 0xFF,
    machine_code & 0xFF,
};

根本不需要调用stringstream