将 C++ 字符串传递给 C 库以进行内存管理

Passing C++ String to C libraries for memory management

我正在尝试使用 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] = '[=10=]';
    std::cout << c << std::endl; // ABCDEFGHIJ
    delete [] c;

    std::string s(10, '[=10=]');
    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, '[=10=]'));

    // 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] = '[=10=]';
    }
    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;
}

对于数组的数组,可以存储一个vector<char*>,它指的是已经动态分配的std::vector<std::string>的开始。

int main()
{
    std::vector<std::string> v(5, std::string(10, '[=10=]'));
    std::vector<char*> vc(5);
    for (int i = 0; i < 5; ++i)
        vc[i] = &(v[i])[0];

    CStrings(&vc[0], 5, 10);

    for (int i = 0; i < 5; ++i)
        std::cout << v[i] << std::endl;

    return 0;
}