将多个字符串传递给函数,从 C++ 代码到 C 代码会引发错误

Passing multiple string to a function from c++ code to c code throw an error

我有一个结构如下

struct st
{
        std::string name;
        std ::string refer;
        int number;
        std::string path;
};

已将上述结构的数组创建为

struct st var[5]={{"rick1","ross1",1,"demo1"},
                { "rick2","roos2",2,"demo2" },
                { "rick3","roos3",3,"demo3"},
                {"rick4","roos4,4,"demo4"},
                {"rick5","roos5",5,"demo5"}};

现在我将我的用户定义函数(通过)称为

c++代码

for(i=0;i<5;i++)
pass(var[i].name.c_str());// how can i pass  name sting to char *?

c代码

void pass(char *name) //  implemented in c code so cannot use string
{
cout<<name<<endl;

}

我应该在调用函数(c++ 代码)中将字符串类型的名称传递给 char * 类型的被调用函数(c 代码)。我使用 c_str() 但它抛出错误.请帮助我提前谢谢

注意:传递函数是从 c++ 代码调用的,它将字符串作为参数传递给 c 代码,c 代码捕获为 char *

name.c_str()returns一个const char*。您不能将 const 指针作为参数传递给采用 non-const 指针的函数。

如果您有最新的编译器,您也许可以使用 std::string::data(),自 C++17 标准以来,它具有 non-const 重载。

否则你需要 const_cast:

pass(const_cast<char*>(var[i].name.c_str()))

我在这里假设 pass 函数实际上并没有修改字符串。