【问题标题】:Passing multiple string to a function from c++ code to c code throw an error将多个字符串从 c++ 代码传递给函数到 c 代码会引发错误
【发布时间】:2017-02-19 12:01:12
【问题描述】:

我有一个结构如下

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++ 代码调用 pass 函数,将字符串作为参数传递给 c 代码,c 代码捕获为 char *

【问题讨论】:

  • 请阅读this c_str reference。注意它返回的是什么类型。
  • 如果是你的用户定义函数,正确定义,即使用std::string&amp;参数。请注意,在 *new* c++11 中,您有 std::string::data
  • @Biffen OP 然后会使用char const* 并且不会有问题。
  • 我只是对感到困惑“这不是有效的选择,因为 char * 在我的情况下会不断变化”。 OP要修改吗?
  • @LogicStuff 感谢您的回复。我无法更改函数定义,因为它是 c 代码和 m 从 c++ 代码调用

标签: c++ string struct char-pointer


【解决方案1】:

name.c_str() 返回一个const char*。您不能将 const 指针作为参数传递给采用非常量指针的函数。

如果您有一个非常新的编译器,您可以使用自 C++17 标准以来具有非常量重载的 std::string::data()

否则你需要一个 const_cast:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    相关资源
    最近更新 更多