简体   繁体   English

在共享缓冲区内存中创建:: std :: string对象

[英]Creating an ::std::string object in the shared buffer memory

I am using Google protobuf in an embedded application with limited heap memory. 我在具有有限堆内存的嵌入式应用程序中使用Google protobuf。 I am currently trying to make the application to use dynamic allocation only as a last resort. 我目前正在尝试使应用程序仅使用动态分配作为最后的手段。 For this, I have some shared buffer on which I create all the proto messages or most of them. 为此,我有一些共享缓冲区,我在其上创建所有原型消息或大部分。 Everything seems to be Ok, except for the cases where the proto message expects a ::std::string parameter. 除了proto消息需要::std::string参数的情况外,一切似乎都没问题。

The way I understand the ::std::string constructors description, is that it will create a copy of the data I supply. 我理解::std::string构造函数描述的方式是,它将创建我提供的数据的副本。 For example this constructor: 例如这个构造函数:

s = new(sharedBufferAddress) ::std::string(mApn, mApnSize);

where 哪里

char                        mApn[APN_MAX_SIZE];
int8_t                      mApnSize;

will create an object located at the sharedBufferAddress, but the data inside will be copied on a buffer assigned on the heap. 将创建一个位于sharedBufferAddress的对象,但内部数据将被复制到堆上分配的缓冲区中。

The question is whether there is some way to have the pointer that is returned by the c_str() function to some specified address. 问题是是否有某种方法可以将c_str()函数返回的指针指向某个指定的地址。

You can not do much to hack the implementation of std::string . 你无法破解std::string的实现。 All attempts will do something illegal and potentially result with undefined behaviors. 所有尝试都会做一些非法的事情,并可能导致未定义的行为。

One option is to evolve custom implementation of Protobuf or custom modifications of stock Protobuf. 一种选择是开发Protobuf的定制实现或Protobuf库存的自定义修改。

Other option is to use existing custom implementations. 其他选项是使用现有的自定义实现。 For example Finnish programmer Petteri Aimonen has implemented Protobuf implementation Nanopb in C for embedded development and released it under zlib license. 例如,芬兰程序员Petteri Aimonen已经在C中实现了Protobuf实现Nanopb嵌入式开发,并在zlib许可下发布了它。 That can be likely more useful than custom modified stock Protobuf in your embedded project since C and C++ work passably well together. 这可能比嵌入式项目中定制的修改后的Protobuf更有用,因为C和C ++可以很好地协同工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM