c++ - 将 C++ 字符串传递给 C 库以进行内存管理
问题描述
我正在尝试使用 C 库,它要求我传入动态分配的 c 字符串以供函数修改。但是,我想避免使用 new/delete 运算符,因为我觉得由 STL 库而不是我自己完成内存管理是更好的做法。
下面,我尝试使用 std::string (和向量)来解决这个问题,并在将它们传递给 C 函数之前预先分配它们。带有一个字符串(CChar,CVoid)的示例有效,但我仍然不确定这是否是正确的方法,或者即使它是一种安全的方法(无错误)。使用向量似乎根本不起作用。
我已经包含了“C”方式来做我想要为字符串和向量实现的目标。
#include <string>
#include <iostream>
#include <vector>
// ----------------------------------------------------
// Example C library Code
void CChar(char* data, int len)
{
int i;
for (i = 0; i < len; ++i)
data[i] = 'A' + (i % 26);
}
void CVoid(void* data, int len)
{
char* d = (char*)data;
int i;
for (i = 0; i < len; ++i)
d[i] = 'Z' - (i % 26);
}
void CStrings(char** strings, int count, int lengths)
{
int i, j;
for (i = 0; i < count; ++i)
for (j = 0; j < lengths; ++j)
strings[i][j] = 'A' + ((i * j + i) % 26);
}
// ----------------------------------------------------
// C++ code
int main()
{
// Traditional way, using new/delete.
char* c = new char[11];
CChar(c, 10);
c[10] = '\0';
std::cout << c << std::endl; // ABCDEFGHIJ
delete [] c;
std::string s(10, '\0');
CChar(&s[0], 10);
std::cout << s << std::endl; // ABCDEFGHIJ
CVoid(&s[0], 10);
std::cout << s << std::endl; // ZYXWVUTSRQ
std::vector<std::string> v(5, std::string(10, '\0'));
// Traditional way with arrays of arrays.
char** cc = new char*[5];
for (int i = 0; i < 5; ++i)
{
cc[i] = new char[11];
cc[i][10] = '\0';
}
CStrings(cc, 5, 10);
for (int i = 0; i < 5; ++i)
{
std::cout << cc[i] << std::endl; // AAAAAAAAAA, BCDEFGHIJK, CEGIKMOQSU, DGJMPSVYBE, EIMQUYCGKO
delete [] cc[i];
}
delete [] cc;
// Doesn't compile
// CStrings(&v[0], 5, 10);
// for (int i = 0; i < 5; ++i)
// std::cout << v[i] << std::endl;
return 0;
}
总结:有没有什么好的方法可以使用C++的STL库,这样我在尝试使用C库的时候就不需要自己做资源管理了。
编辑:清理数组时出错
解决方案
当然,您可以只使用std::vector<char>
您不想考虑分配的情况。这是你如何做到的:
#include <vector>
int main()
{
std::vector<char> str(100, 0); //Allocate an array of 100 chars and initialize them to 0
SomeFunction(&str[0], str.size()); //Pass the address to the array and its size
return 0;
}
推荐阅读
- sql - 当整列存储为文本时,如何在SQL中分隔数字和文本?
- php - 如何为 RabbitMQ PHP 任务创建 Docker 容器
- javascript - 无法使用 async 和 Foreach 处理 Firebase 获取的值
- javascript - 如何在使用 sinon 的包装器中调用对象时进行单元测试?
- shopify - 使用 Cart.js 和 Rivets.js 添加/删除购物车项目
- python - Python Multiprocessing/Pool with Selenium - 创建 webdriver 的多个副本
- javascript - 在 && 运算符中更改 CSS 样式
- javascript - Javascript slick.js轮播将多个幻灯片向后拖过第一个元素不起作用
- java - Maven 没有检测到 Reactor 构建模块中的依赖关系?
- sql - 滚动总和直到达到某个值,加上计算的持续时间