加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C函数参数列表中有String类型时,我可以使用C程序函数调用C函数

发布时间:2020-12-16 10:34:33 所属栏目:百科 来源:网络整理
导读:我的C程序应用程序需要调用C函数.但是C函数中有字符串类型.例如,我需要像这样写一个函数fooC(): //main.c:void fooC(){ char* str = "hello"; fooCPP(str);}//foo.cppvoid fooCPP(String str){ ......} 如何正确编写代码? 更新 //hello.cpp #include iostr
我的C程序应用程序需要调用C函数.但是C函数中有字符串类型.例如,我需要像这样写一个函数fooC():

//main.c:

void fooC()
{
   char* str = "hello";
   fooCPP(str);
}


//foo.cpp

void fooCPP(String& str)
{
  ......
}

如何正确编写代码?

更新

//hello.cpp 
#include <iostream>
#include <string>
#include "hello.h"
using namespace std;

void fooCpp(char const* cstr){
    std::string str(cstr);
    cout << str <<endl;
}

//hello.h
#ifdef __cplusplus
extern "C"{
#endif
void fooCpp(char const* str);

#ifdef __cplusplus
}
#endif

//main.c
#include "hello.h"

int main()
{
    char* str = "test"  ;
    fooCpp(str);
    return 0;
}

编译:

g -c hello.cpp hello.h

gcc hello.o main.c -g -o main

错误:

hello.o:在函数__static_initialization_and_destruction_0(int,int)’中:
hello.cpp :(.text 0x23):undefined reference tostd :: ios_base :: Init :: Init()’
hello.o:在函数__tcf_0’中:
hello.cpp :(.text 0x6c):undefined reference tostd :: ios_base :: Init :: ~Init()’
hello.o:在函数fooCpp’中:
hello.cpp :(.text 0x80):undefined reference tostd :: allocator :: allocator()’
hello.cpp :(.text 0x99):对std :: basic_string< char,std :: char_traits< char&gt ;,std :: allocator< char>的未定义引用> :: basic_string(char const *,std :: allocator< char> const&)’
hello.cpp :(.text 0xa4):undefined reference tostd :: allocator :: ~partdator()’……………………… …
………………………………

解决方法

不.你需要在C中编写一个包装器:

//foo.cpp

void fooCPP(std::string& str)
{
  ......
}

extern "C" void fooWrap(char const * cstr)
{
    std::string str(cstr);
    fooCPP(str);
}

并从C调用它:

/*main.c:*/
extern void fooWrap(char const * cstr); /*No 'extern "C"' here,this concept doesn't exist in C*/

void fooC()
{
    char const* str = "hello";
    fooWrap(str);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读