好的,我正在編輯我的原始帖子。很抱歉之前不夠清楚。我對開發人員角色比較陌生,特別是 C、C 、Python 和嵌入式 Linux。
有一個python串列plist = [2,434]
該資料被發送到另一個使用套接字編程用 C 撰寫的程式。
plist = str(plist)
sock = socket.socket(socket.AF_INET, socket.SOCK_STRREAM)
sock.connect(('localhost',12345))
sock.send(plist.encode('utf-8'))
sock.close()
現在這個資料被 C 程式接收為一個字串。我剛剛制作了一個示例字串,如下所示,讓您了解我在 C 端得到了什么。
const char* construct= "[2,434]";
現在我試圖將兩個數字 2 和 434 分別分配給playerType和playerID,它們是以下稱為PLAYER_HEADER的結構的一部分。
typedef enum
{
START,
STOP,
PAUSE,
RECORD
}PLAYER_TYPE;
typedef struct
{
PLAYER_TYPE playerType;
unsigned long playerID;
}PLAYER_HEADER;
到目前為止,我已經嘗試過這種方法,我將字串型別轉換為結構型別。
PLAYER_HEADER* p= (PLAYER_HEADER* ) construct;
player = p->playerType;
cout<<(char)player<<endl;
但這僅列印 ' [ ' 這是[2,434]的第一個字符
I would like to know why this is happening. Is there a way I can get the rest of the data?
I get that I have typecasted as a character.
My end goal is to assign the two numbers to playerType and playerID .
Is there any other way I can do this? Or is there a concept in C I need too understand to solve this problem?
uj5u.com熱心網友回復:
C 是一種強大的語言,但它的一部分功能是讓你做一些不“正確”的事情。您嘗試將 achar *轉換為 a PLAYER_HEADER*just 的方式并沒有像您期望的那樣作業。您需要決議字串,忽略不需要的部分并將保留的部分轉換為正確的資料型別。
一種方法是使用std::stringstream:
PLAYER_HEADER player;
std::istringstream ss(construct);
int temp;
ss.ignore(100, '['); // Skip [
if (ss >> temp) {
player.playerType = (PLAYER_TYPE)temp;
ss.ignore(100, ','); // Skip ,
if (ss >> player.playerID) {
// Success. Do something.
}
}
另一種選擇是正則運算式:
PLAYER_HEADER player;
std::smatch match;
std::regex re(R"(\[(\d ),(\d )\])");
std::string construct_str(construct);
if (std::regex_search(construct_str, match, re)) {
playerType = (PLAYER_TYPE)std::stoi(match[1]);
playerID = std::stoi(match[2]);
// Success. Do something.
}
還有其他方法,但重點是您需要了解為什么您的投射不起作用。使用您的代碼:
PLAYER_HEADER* p= (PLAYER_HEADER* ) construct;
player = p->playerType;
cout<<(char)player<<endl;
p指向第一個字符,"[2,434]"其中是 a [。然后playerType很可能在結構中有一個偏移量,0所以player最終也指向[. 然后,當您將其列印為 a 時,char您將得到[.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/425697.html
標籤:python c pointers struct enums
