c++ - 从 C 调用 C++ 非成员函数

标签 c++

我想将模板函数实例的指针作为回调传递给 C 函数。而且在extern "C"中声明模板显然是不可能的。

是否保证 C++ 对非成员函数使用与 C 相同的调用约定?在 extern "C" 中声明一个函数除了防止不兼容的名称重整之外还有其他效果吗?

最佳答案

直接为 C 库导出 C++ 方法或模板函数不是一个好主意。如果我有一个 C++ 程序,那么我通常将 C 绑定(bind)放入其单独的 .cpp + .h 文件对中,并用 extern "C" block 包围头文件,我只使用 C 兼容函数那里的声明。在随附的 .cpp 文件中,您实现了这些功能,并且由于它是一个 .cpp 文件,您可以在绑定(bind)功能的实际实现中访问 C++ 功能(模板、类等),即使它们的签名是 C 兼容的,使用 C-friendly类型。

在您的情况下,您应该将 C 绑定(bind)函数放入此 binder .cpp+.h 文件中,并且通过该函数的实现,您将能够轻松调用指定模板函数的实例。

简单愚蠢的例子:

CBindings.h:

// This is the header used by both C++ and C
#ifdef __cplusplus
extern "C" {
#endif

    // C compatible function declarations with C-friendly types.
    int int_from_string(const char* s);

#ifdef __cplusplus
}
#endif

CBindings.cpp:

#include "CBindings.h"
#include "WhateverCPPHeader.h"

int int_from_string(const char* s)
{
    // Since the implementation is in a .cpp file here we can do C++ish things.
    return FromString<int>(s);
}

WhateverCPPHeader.h:

// Somewhere in your C++ header files:
template <typename T>
T FromString(const std::string& s);

...
// Template specializations of FromString for several T types
...

Whatever.c:

#include "CBindings.h"
#include <stdio.h>

void my_c_func(void)
{
    int i = int_from_string("5");
    printf("%d\n", i);
}

这适用于所有平台,没有问题,并且 C/C++ 之间的切割被清楚地分离到它自己的文件中。

关于c++ - 从 C 调用 C++ 非成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22272666/

相关文章:

c++ - Boost.uBLAS 中的矩阵表达式和 vector 表达式类是什么?

c++ - 针对 Windows 7 桌面 : identifier "SHGetKnownFolderPath" is undefined

c++ - 修改 CUDA 和 cpp Makefile

C++ unordered_set vector

c++ - 读取显存数据

c++ - 如何在SFML中使用俄语文本?

c++ - 使用字符串文字初始化 vector<char>

c++ - 英特尔 C/C++ 编译器在数组初始化期间抛出错误

c++ - 如何正确接收来自管道的数据?

c++ - 从不同的变量模板类型构建变量的模板类型