在C函数参数列表中有String类型时,我可以使用C程序函数调用C函数
我的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)’中: 解决方法
不.你需要在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); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |