我正在使用C创建程序.但是,我需要使用许多只有C++的API.那么,我是否有可能在C++中创建共享对象,然后使用C访问其功能?
如果无法连接这些代码,我如何从C++代码获取信息到C代码?我尝试从C调用C++函数,但是当我包含时,我在链接期间遇到错误<string>.所以当我从C调用C++函数时,我应该只使用那些与C编译器兼容的代码吗?
#ifndef CPPFILE_H
#define CPPFILE_H
#ifdef __cplusplus
extern "C" {
#endif
extern int myfunction(const char *filename);
#ifdef __cplusplus
}
#endif
#endif
Run Code Online (Sandbox Code Playgroud)
#include "cppfile.hpp"
#include <string>
int myfunction(const char *filename) {
String S(filename);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
#include "cppfile.hpp"
int main(int argc, char **argv)
{
int i = myfunction(argv[1]);
printf("%d\n", i);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
gcc -c cmain.c
g++ -fPIC -shared -o cppfile.so cppfile.cpp
Run Code Online (Sandbox Code Playgroud)