C 代码需要从 C++ 代码中获取 void 指针,类似
void *get_map_from_cpp(); /* declare the function */
void *our_map = get_map_from_cpp();
get_map_from_cpp() 将被定义为(在 C++ 中)类似的东西;
#include <map>
#include <string>
extern "C" void *get_map_from_cpp()
{
std::map<std::string, float> *the_map = new std::map<std::string, float>;
return static_cast<void *>(the_map);
}
但它并不止于此。要将值插入映射中,我们需要将值传入,例如,在 C 中
void insert_to_map(void *, const char *str, float f); /* declaration */
insert_to_map(our_map, "Everything", 42.0);
其中insert_to_map() 也必须在 C++ 中定义,例如
extern "C" void insert_to_map(void *m, const char *str, float f)
{
std::map<std::string, float> *the_map;
the_map = static_cast< std::map<std::string, float> *>(m);
std::string the_str(str);
(*the_map)[the_str] = f;
}
同样,retrieve_from_map() 可以实现为
extern "C" float retrieve_from_map(void *m, const char *str)
{
std::map<std::string, float> *the_map;
the_map = static_cast< std::map<std::string, float> *>(m);
std::string the_str(str);
std::map<std::string, float>::const_iterator i = the_map->find(the_str);
if (i != the_map->end())
return i->second;
else
return 0.0f; // string not found in map, so return 0.0
}
从 C 调用的函数必须提供纯 C 接口 - 这意味着 C 代码不能直接接触 C++ 类型。其次,到 C++ 的映射必须仅在 C++ 代码中完成,因为 C 编译器不会理解这些结构。这意味着函数必须只接受或返回在 C 中有意义的类型,函数必须为 C++ 编译器声明为 extern "C"(以便可以从 C 调用),并且函数的主体必须处理从将 C 类型转换为 C++。
这确实依赖于 C 和 C++ 编译器之间的兼容性(例如,来自同一供应商、兼容的 ABI 等)。