将常量char数组转换为unsigned char指针的问题

时间:2014-03-22 02:04:53

标签: c++ casting enet

我一直在做一个项目和男孩哦,男孩在这个问题上受伤了。我正在使用名为“enet”的网络库,我正在尝试分配连接信息的客户端。使用网站上的教程,我使用:server.event.packet->data = "client info";但是,enet抱怨字符串不是“unsigned char *”。这是构建日志(使用clang ++进行编译):

./network.h:9:14: warning: in-class initialization of non-static data member accepted as a C++11 extension [-Wc++11-extensions] int clients = 0; ^ main.cpp:142:28: error: assigning to 'enet_uint8 *' (aka 'unsigned char *') from incompatible type 'const char [12]'; server.event.packet->data = "client info"; ^ ~~~~~~~~~~~~~

我已经尝试了我能想到的所有类型的铸件,并且我已经搜索过,但似乎没有任何效果。我不能让这件事变得快乐。

Main.cpp的:

#include <iostream>
#include <string>
#include <sstream>
#include <istream>
#include <cstring>
#include <cstdio>
#include <unistd.h>
#include <stdio.h>
#include "network.h"
#include "clients.h"
#include "config.h"

void runCommand(std::string command);
int startNetwork();
void shutdownNetwork();
void addClientRecord();
std::string getUsername();

std::string username;

bool manualInput = false;
bool debug = true;

int iPeerCount = 0;

Server server;

int main(int argc, char ** argv){
    std::string currentCommand;

    if(manualInput==true){
        std::cout << "Please type a command: ";
        std::getline(std::cin,currentCommand);
        if(debug == true){
            std::cout << currentCommand << std::endl;
        }
        runCommand(currentCommand);
    }

    startNetwork();

    atexit(shutdownNetwork);

    return 0;
}

int startNetwork(){
    if (enet_initialize () != 0){
        std::cout << "\nAn error has occured while initializing ENet.\n";
        return EXIT_FAILURE;
    }
    server.startServer();
    return 1;
}

void shutdownNetwork(){
    enet_deinitialize();
}

int Server::startServer(){

//  server.serverOne = enet_host_create (& server.address, 32, 2, 0, 0);

//  if(CUSTOM_HOST == true){
//      enet_address_set_host(&address, HOST);
//  } else {
    server.address.host = ENET_HOST_ANY;
//  }
    server.address.port = PORT;

    server.serverOne = enet_host_create( & server.address, 32, 2, 0, 0);

        if(debug==true){
                printf("[NETWORK] Host: %x \n[NETWORK] Port: %u\n", server.address.host, address.port);
        }

    if(server.serverOne==NULL){
        std::cout << "\nAn error has occured while starting the ENet server.\n";
        exit (EXIT_FAILURE);
    }

    monitor();
    return 1;
}


void Server::monitor(){
    int clients = 0;
    if(debug==true){
        printf( "[NETWORK] Waiting for commands...\n" );
    }
    printf("[NETWORK] Server online, awaiting commands and/or connections...\n");
    scan_network:
    while(enet_host_service (serverOne, & event, 1000) > 0){
        switch(event.type){
            case ENET_EVENT_TYPE_CONNECT:
                clients++;
                printf("[INFO] New connection from: %x:%u.\n", event.peer -> address.host, event.peer -> address.port);
                addClientRecord();
    /*          for(int x=0;x<32;x++){
                    if(clients[x].name != ""){ }
                    else{
                        clients[x].name = "full";
                    }
                }*/
                break;
            case ENET_EVENT_TYPE_RECEIVE:
                if(debug==true){ printf("A packet of length %lu containing %s was received from %s on channel %u.\n", event.packet -> dataLength, event.packet -> data, event.peer -> data, event.channelID); }
                runCommand(reinterpret_cast<const char*>(event.packet -> data));
                enet_packet_destroy(event.packet);
/*              printf("Disconnect client %s ? ", event.peer -> data);
                gets(buffer);
                std::cout<<buffer<<std::endl;
                if(buffer=="yes"){
                    enet_peer_disconnect(event.peer, 0);
                }*/   //Do not use until fixed or spam!
                break;
            case ENET_EVENT_TYPE_DISCONNECT:
                clients--;
                printf("%s disconnected.\n", event.peer -> data);
                event.peer -> data = NULL;
            case ENET_EVENT_TYPE_NONE:
                break;
        }
    }
    goto scan_network;
}

void runCommand(std::string command){
    if((command == "disconnect") || (command == "Disconnect") || (command=="DISCONNECT")){
        enet_peer_disconnect(server.event.peer,0);
        printf("[INFO] Client %s issued the disconnect command.\n", server.event.peer -> data);
    }
}

std::string getUsername(){
    return username;
}

void addClientRecord(){
    std::string bufferName = ("client " + server.clients);
    server.event.packet->data = "client info";
}

Network.h:

#include <enet/enet.h>

class Server {
    public:
    ENetAddress address;
    ENetHost * serverOne;
    ENetEvent event;

    int clients = 0;

    int startServer();
    void monitor();
};

非常感谢任何想法和帮助。干杯!

1 个答案:

答案 0 :(得分:0)

据我所知,serverServer类型的结构,其字段eventENetEvent,其字段packet属于类型_ENetPacket*及其字段数据为unsigned char*。那么现在是什么hapening:你在堆栈上创建一个сstring,然后将第一个元素的地址分配给全局对象的data字段,然后你离开函数和指针仍然存活,而那里存储的数据不再存在avaliable。这就是为什么在使用正确的类型转换unsigned char*时遇到段错误的原因。 所以你应该做到以下几点:

void addClientRecord()
{
  std::string bufferName = ("client " + server.clients);
  char* clientName = "client info";
  // Allocate mem
  char* data = new unsigned char[strlen(clientName)];
  // Copy string there
  strcpy(data, clientName);
  // Store pointer
  server.event.packet->data = (unsigned char*)data;
}

并且不要忘记清除分配的内存。那是因为你应该总是检查server.event.packet->data是否包含非nullptr值,如果是,则删除并仅分配。你应该为Server提供一个析构函数,它将删除该字符串,如果有任何存在和构造函数在开始时写入nullptr,那么你不会删除一些垃圾邮件地址,这肯定会导致崩溃。但首先,您需要确定_ENetPacketENetEvent类是否为上述data提供了任何功能。这就是cstrings的工作方式。

P.S。应该有一个编译器标志,默认情况下会将char切换为无符号。