是否可以在 DLL 中导出具有 C 链接的 C++ 成员方法

Is it possible to export a C++ member method with C linkage in a DLL?

本文关键字:链接 成员方法 C++ DLL 是否      更新时间:2023-10-16

在 cpp 文件中考虑这一点:

struct someStruct{
    public:
    extern "C"  __declspec(dllexport) int sumup();
} someStruct;
extern "C" __declspec(dllexport) int someStruct::sumup()
{
    return 0;
}

这不会编译:error: expected unqualified-id before string constant是否无法导出具有 C 链接的 C++ 成员方法?

首先,链接规范不适用于成员函数; 通过 [dcl.link]/4:

[...]链接规范应仅在命名空间范围 (3.3) 中出现。[...]

但是,在同一段中,标准中甚至有一个与您的问题相关的示例:

[...]在确定类成员名称的语言链接和类成员函数的函数类型时,将忽略 C 语言链接。[示例:

extern "C" typedef void FUNC_c();
class C {
  void mf1(FUNC_c*);      // the name of the function mf1 and the member
                          // function’s type have C ++ language linkage; the
                          // parameter has type pointer to C function
  FUNC_c mf2;             // the name of the function mf2 and the member
                          // function’s type have C ++ language linkage
  static FUNC_c* q;       // the name of the data member q has C ++ language
                          // linkage and the data member’s type is pointer to
                          // C function
};
extern "C" {
  class X {
    void mf();            // the name of the function mf and the member
                          // function’s type have C ++ language linkage
    void mf2(void(*)());  // the name of the function mf2 has C ++ language
                          // linkage; the parameter has type pointer to
                          // C function
  }
};

结束示例]

No. 它不是那样工作的。 它根本不起作用。 做不到。 没办法不行。