C++从 C 调用的共享库

发布于 2024-12-22 13:26:01 字数 195 浏览 1 评论 0原文

我有一个用 C++ 编写的共享库。它导出一个由 extern "C" 函数组成的可见接口,用于创建、销毁和操作不透明类型。

现在,我想要一个使用这个库的纯 C 程序。

我可以这样做(独立于平台)吗?如果 main 不是用 C++ 编写的,C++ 运行时和 C++ 静态对象什么时候会被初始化?

I have a shared library written in C++. It exports a visible interface made of extern "C" functions which create, destroy and manipulate opaque types.

Now, I'd like to have a pure C program which uses this library.

Can I do this (platform independently) ? When will the C++ runtime and the C++ static objects get initialized if main is not written in C++ ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

挽你眉间 2024-12-29 13:26:01

初始化阶段取决于平台。
对于 Linux,动态加载的库可以具有专门声明的符号,在加载库时由 dlopen() 自动调用这些符号。

有关详细信息,请参阅 dlopen(3) 手册页的“过时符号 init() 和 fini()”部分。

静态初始值设定项隐式标记为 __attribute__((constructor)) ,因此通常您无需执行任何特殊操作即可在加载共享库时调用它们。我怀疑这在其他平台上是相同或相似的。

The initialization phase is platform dependent.
In the case of Linux, dynamically loaded libraries can have specially declared symbols that are automatically called by dlopen() when the library is loaded.

See the manpage for dlopen(3), section The obsolete symbols init() and fini() for more info.

Static initializers are implicitly marked as __attribute__((constructor)), so in general you don't have to do anything special to have them called when the shared library is loaded. I suspect this is the same or similar on other platforms.

楠木可依 2024-12-29 13:26:01

我可以这样做(独立于平台)吗?

库加载是依赖于平台的操作。

C++运行时和C++静态对象何时初始化
如果 main 不是用 C++ 编写的?

没关系。它们将在进入主程序之前初始化。

Can I do this (platform independently) ?

The library loading is a platform dependent operation.

When will the C++ runtime and the C++ static objects get initialized
if main is not written in C++ ?

Doesn't matter. They will be initialized before the main is entered.

╭ゆ眷念 2024-12-29 13:26:01

通常,共享库系统有自己的入口点来完成这项工作,而不是 main,但 DLL 有一个 DLLMain,实现可以在其中放置此类代码。然而,在一般情况下,这不关你的事,而是你用来处理这个问题的任何编译器的工作。

Usually, shared library systems have an entry point of their own in which to do this work, not main but DLLs have a DLLMain where the implementation can put such code. However, in the general case, it is none of your business and it's the job of whatever compiler you used to deal with this issue.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文