如何从C调用模板化的C++自由函数?

wb1gzix0  于 9个月前  发布在  其他
关注(0)|答案(2)|浏览(95)

我想把一个函数模板的示例的指针作为回调传递给一个C函数。显然不可能把模板声明为extern "C"
是否保证C++对非成员函数使用与C相同的调用约定?在extern "C"中声明函数除了防止不兼容的名称损坏外,还有其他效果吗?

a0zr77ik

a0zr77ik1#

直接为C库导出C方法或模板函数是一个坏主意。在C代码库中,我通常将C绑定放入专用的.cpp + .h文件对中-头文件必须使用extern "C"块和C兼容的函数声明。在附带的.cpp文件中,您可以实现C函数,因为它是一个.cpp文件,所以您可以访问C特性(模板、类、C函数等)。
范例:

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)
{
    // We can use C++ features because the implementation is in a .cpp file.
    return FromString<int>(s);
}

验证CPPHeader.h:

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

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

无论如何.c:

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

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

gpfsuwkq

gpfsuwkq2#

不能。不能保证它使用相同的调用约定。你可以使用调用约定修饰符,如_stdcallcdeclpascal等。所以你必须确保双方都知道相同的调用约定。
一种方法是检测被篡改的名称并为C函数定义一个适当的原型。
考虑改变设计;因为你不能从C中的模板中受益,你可以定义一个简单的C++函数(定义为extern“C”)来调用模板化的函数。

相关问题