通过外部“C”对C ++对象的接口功能 [英] Interface to C++ objects through extern "C" functions

查看:121
本文介绍了通过外部“C”对C ++对象的接口功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以 externC函数接受或返回C ++特定的数据类型,例如引用,指针成员或非POD类)?我不能在禁止这个C ++标准中找到任何东西。逻辑上,我希望标准说一些关于它,因为C ABI不一定适合传递这样的类型。

Can an extern "C" function accept or return C++-specific data types, such as references, pointers-to-members, or non-POD classes (by value)? I cannot find anything in the C++ standard that forbids this. Logically, I would expect the standard to say something about it, as the C ABI is not necessarily suitable for passing such types around.

我想要使用C链接与C编译器无关。该函数仅从C ++代码调用。我只是想从我的动态库导出未解析的函数名称。

The reason for me wanting to use C linkage has nothing to do with C compilers. The function is called only from C++ code. I just want to export unmangled function names from my dynamic libraries.

一个愚蠢的代码示例:

class Foo {
  public:
    virtual void doit() = 0;
};

class Bar : public Foo {
  public:
    void doit() { std::cout << "Bar" << std::endl; }
};

extern "C" Foo& getFoo() { static Bar bar; return bar; }

extern "C" Bar getBar() { return Bar(); }

这将在Linux上与GCC一起编译,并按预期工作。是否应该标准化?

This compiles with GCC on Linux, and works as expected. Should it, standard-wise?

问题是对注释中的讨论的后续行动这个问题

The question is a follow-up to a discussion in the comments to this question.

更新我已经用Comeau编译器测试过了, 。

Update I have tested this with the Comeau compiler, it didn't complain.

推荐答案

根据7.5.9链接规范(c ++ 11草稿)http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242 .pdf

According to section 7.5.9 Linkage specifications (c++11 draft) http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf

从C ++到其他语言定义的对象和C ++中从其他语言定义的对象的链接是实现定义和语言相关的其中两个语言实现的对象布局策略是相似的,可以实现这种链接。

"Linkage from C++ to objects defined in other languages and to objects defined in C++ from other languages is implementation-defined and language-dependent. Only where the object layout strategies of two language implementations are similar enough can such linkage be achieved."

这篇关于通过外部“C”对C ++对象的接口功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆