簡體   English   中英

C ++將字節從char *傳遞到BYTE *

[英]C++ Pass bytes from char* to a BYTE*

我想知道如何將表示為char*的字節序列傳遞/復制到Windows中的C ++中的BYTE*

假設我有這個char*

const char *ByteString = "\x3B\xC8\x74\x1B"  

如何將每個字節從此char *復制到BYTE *Bytes ,反之亦然?

編輯:非常感謝大家的幫助!

BYTE的定義是:

typedef unsigned char BYTE;

這是不一樣的一個const char ,所以你需要將它轉換,但要注意,虛擲const從一些宣稱const下手導致不確定的行為,並試圖真正改變數據帶來更大的風險。

BYTE* Bytes = reinterpret_cast<BYTE*>(const_cast<char*>(ByteString));

編輯:我剛剛注意到將const char*轉換為BYTE*已經被解決了,但我現在暫時將它留在這里。


復制數據(不是零終止字符串)可以這樣做:

const char ByteString[] = "\x3B\xC8\x74\x1B";
BYTE* Bytes = new BYTE[sizeof(ByteString)-1];
std::memcpy(Bytes, ByteString, sizeof(ByteString)-1);

// Use your Bytes

delete[] Bytes; // manual delete when you are done

或更好:

const char ByteString[] = "\x3B\xC8\x74\x1B";
std::basic_string<BYTE> Bytes( reinterpret_cast<const BYTE*>(ByteString), sizeof(ByteString)-1 );

// use Bytes
// Bytes.data()  returns a BYTE*
// Bytes.size()  returns the length.

但鑒於您正在做的事情的性質,您可以跳過這些轉換並使用正確類型的數組開頭:

BYTE Bytes[] = { 0xA1, 0x00, 0x00, 0x00, 0x00, 0x3B, 0xC8, 0x74, 0x1B };

要么

std::basic_string<BYTE> Bytes({ 0xA1, 0x00, 0x00, 0x00, 0x00, 0x3B, 0xC8, 0x74, 0x1B });

當您處理的是原始BYTE數據時,這些不需要任何轉換。 這是一個使用ReadProcessMemorybasic_string作為緩沖區和模式的示例。

using BYTEstr = std::basic_string<BYTE>; // just for convenience

BYTEstr Buffer(1024, 0); // 1024 BYTES initialized with 0
BYTEstr Pattern({ 0xA1, 0x00, 0x00, 0x00, 0x00, 0x3B, 0xC8, 0x74, 0x1B });

ReadProcessMemory(hProcess, lpBaseAddress, Buffer.data(), Buffer.size(), &lpNumberOfBytesRead);

BYTEstr::size_type pos = Buffer.find(Pattern);

if (pos == BYTEstr::npos) {
    std::cout << "Pattern not found\n";
} else {
    std::cout << "Pattern found at position " << pos << "\n";
}

要尊重const,請使用

const BYTE *Bytes = reinterpret_cast<const BYTE*>(ByteString);

反之亦然:

const char *ByteString = reinterpret_cast<const char *>(Bytes);

如果要復制緩沖區以便修改它,請使用

len = LenOfChrStr;
BYTE *Bytes = new BYTE[len];
memcpy(Bytes, ByteStr, len);

給定一個char const *字符數組,我們可以創建一個帶有readwrite BYTE的新緩沖區,以便API可以編輯:

char const *ByteString = "\x3B\xC8\x74\x1B";
auto len = std::strlen(ByteString) + 1;
auto ptr = std::make_unique<BYTE[]>(len);
std::memcpy(ptr.get(), ByteString, len);

如果你需要將內存的所有權交給函數:

Func(ptr.release());

但是如果你想自己保留所有權:

Func(ptr.get());

在MSVC中(我想這是你的WinAPI應用程序的編譯器)你可以使用/J選項使char類型無符號(更多這里: https//docs.microsoft.com/en-us/cpp/build/reference/j- default-char-type-is-unsigned?view = vs-2017 )。 如果這樣做, BYTEchar相同,不需要轉換。

請注意,這可能會在您的應用程序中產生一些其他副作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM