我编写了一段代码,该代码在内部使用C ++ STL(std :: vector)存储一些信息,然后通过类似于C的函数提供该信息,稍后将在Windows DLL中将其导出。我想知道这种方式是否正确和稳定。如果在该领域有一定经验的人可以向我确认没问题或向我指出问题,将不胜感激。 这只是一个示例示例,所有错误处理功能将在以后添加。
#include <iostream>
#include <string>
#include <vector>
typedef struct _c_vector_wrapper_config
{
size_t currentPosition = -1;
// for std::string
std::vector<std::string> *vPointer = nullptr;
std::vector<std::string>::iterator vIterator;
// for C null terminated string
// we support 2 type of vectors to have ability to work with C like strings from other than C++
// languages
// Also we allocate memory for this string using C runtime malloc and at the end we can easily free
// this memory to avoid memory leaks.
// Why we use also std::vector<std::string> ? Because STL string operation is more simple and safe
// and we need C like strings only to export them from DLL
std::vector<char*> *vPointerChar = nullptr;
std::vector<char*>::iterator vIteratorChar;
} c_vector_wrapper_config;
c_vector_wrapper_config *vector_wrapper_config = new c_vector_wrapper_config();
// c_vector_wrapper_config *vector_wrapper_config = new c_vector_wrapper_config();
void create_vector();
void delete_vector();
void add_value(std::string value);
char* get_value();
int main(void)
{
create_vector();
add_value("test1");
add_value("test2");
add_value("test3");
std::cout << get_value() << std::endl;
std::cout << get_value() << std::endl;
delete_vector();
return 0;
}
void create_vector()
{
if (vector_wrapper_config->vPointer == nullptr)
{
vector_wrapper_config->vPointer = new std::vector<std::string>();
vector_wrapper_config->vPointerChar = new std::vector<char*>();
}
}
void add_value(std::string value)
{
vector_wrapper_config->vPointer->push_back(value);
std::size_t str_length = value.size();
char *c_string = static_cast<char*>(malloc(str_length +1));
value.copy(c_string, str_length, 0);
c_string[str_length] = '\0';
vector_wrapper_config->vPointerChar->push_back(c_string);
}
char* get_value()
{
vector_wrapper_config->currentPosition++;
char* current_value = (*vector_wrapper_config->vPointerChar)[vector_wrapper_config->currentPosition];
return current_value;
}
void delete_vector()
{
delete vector_wrapper_config->vPointer;
// free memory allocated previously for C like strings
for (std::vector<char*>::iterator it = vector_wrapper_config->vPointerChar->begin(); it != vector_wrapper_config->vPointerChar->end(); ++it)
{
free(*it);
}
}