首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >rabbitmq-c发送nlohmann json

rabbitmq-c发送nlohmann json
EN

Stack Overflow用户
提问于 2021-07-19 11:58:39
回答 1查看 50关注 0票数 1

想通过RabbitMQ-C发送图像,但图像文件太大。接收器无法检索图像。因此,我将图像转换为base64,然后将其放入JSON中。

代码语言:javascript
复制
const char *msg;


FILE *image1;
    if (image1 = fopen(path, "rb")) {
        fseek(image1, 0, SEEK_END); //used to move file pointer to a specific position
                                    // if fseek(0 success, return 0; not successful, return non-zero value
                                    //SEEK_END: end of file
        
        length = ftell(image1); //ftell(): used to get total size of file after moving the file pointer at the end of the file
        sprintf(tmp, "size of file: %d  bytes", length);

//convert image to base64
        std::string line;
        std::ifstream myfile;
        myfile.open(path, std::ifstream::binary);
        std::vector<char> data((std::istreambuf_iterator<char>(myfile)), std::istreambuf_iterator<char>() );
        std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len);
        std::string code = base64_encode((unsigned char*)&data[0], (unsigned int)data.size());
        
//convert std::string to const char 
        const char* base64_Image = code.c_str();
        

        
        json j ;
    
        
        j.push_back("Title");
        j.push_back("content");
        j.push_back(base64_Image);
        
        std::string sa = j.dump();

        msg = sa.c_str();       //convert std::string to const char*
        
    }
    else {
        return;
    }

使用RabbitMQ-C将消息(Msg)发送到接收方,但失败的错误指向此处

const char*不能使用amqp_cstring_bytes(消息)转换为amqp_bytes_t吗??

代码语言:javascript
复制
    respo = amqp_basic_publish(conn, 1, amqp_cstring_bytes(exchange), amqp_cstring_bytes(routing_key),0, 0, NULL, amqp_cstring_bytes(msg));

并得到这个错误

代码语言:javascript
复制
If there is a handler for this exception, the program may be safely continued.```


Anyone know how to send image as JSON using RabbitMQ-C & C++ ?
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-19 16:18:59

amqp_cstring_bytes需要一个C字符串,通常以NUL字节结尾。你的PNG文件几乎保证包含一个NUL字节,所以这就解释了为什么你的消息在中途被切断了。

至于粘贴中的代码:只有在sa处于活动状态且未修改时,sa.c_str()返回的指针才有效。一旦退出包含sa定义的块,该变量就会被埋没。

相反,使用amqp_bytes_alloc获取适当大小的缓冲区并返回:

代码语言:javascript
复制
amqp_bytes_t bytes = amqp_bytes_malloc(sa.length());
strncpy((char *)bytes.bytes, sa.c_str(), sa.length());

然后将bytes对象传递给amqp_basic_publish。完成后,不要忘了使用ampqp_bytes_free

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68434969

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档