【问题标题】:C wrapper for a C++ class not workingC++ 类的 C 包装器不起作用
【发布时间】:2017-09-04 12:26:42
【问题描述】:

我有一个 C++ 库,它公开了一些 API(通过 cppH.h),它是一个静态库 (*.lib)。 我想在 C 代码中使用它,因此编写了一个 C Wrapper,如下所示。但是,我收到如下构建错误。请在这方面帮助我知道我错过了什么。我来自here

cppH.h - C++ 库的头文件

class Abc
{
    int ma, mb;
public:
    void pass(int a,int b);
    int  sum();
};

CWrapper.h

#ifdef __cplusplus
extern "C" {
#endif
    typedef struct Abc_C Abc_C;
    Abc_C* New_Abc();
    void pass_in_C(Abc_C* cobj, int a, int b);
    int  sum_in_C(Abc_C* cobj);
#ifdef __cplusplus
}
#endif

CWrapper.cpp

#include "CWrapper.h"
#include "cppH.h"  
extern "C" {
    Abc_C* New_Abc()
    {
        return new Abc_C();
    }

    void pass_in_C(Abc_C* cobj, int a, int b)
    {
        cobj->pass(a, b);
    }

    int  sum_in_C(Abc_C* cobj)
    {
        cobj->sum();
    }

}

CWrapper.cpp & CWrapper.h 静态链接到 C++ 库 cppH.lib & cppH.h.

编译错误

1>------ Rebuild All started: Project: CApp, Configuration: Debug Win32 ------
1>  CS.c
1>  CWarpperS.cpp
1>c:\users\user1\documents\ccg\vsprojects\expapp\capp\cwarppers.cpp(7): error C2512: 'Abc_C' : no appropriate default constructor available
1>c:\users\user1\documents\ccg\vsprojects\expapp\capp\cwarppers.cpp(12): error C2027: use of undefined type 'Abc_C'
1>          c:\users\user1\documents\ccg\vsprojects\expapp\capp\cwrapper.h(6) : see declaration of 'Abc_C'
1>c:\users\user1\documents\ccg\vsprojects\expapp\capp\cwarppers.cpp(12): error C2227: left of '->pass' must point to class/struct/union/generic type
1>c:\users\user1\documents\ccg\vsprojects\expapp\capp\cwarppers.cpp(17): error C2027: use of undefined type 'Abc_C'
1>          c:\users\user1\documents\ccg\vsprojects\expapp\capp\cwrapper.h(6) : see declaration of 'Abc_C'
1>c:\users\user1\documents\ccg\vsprojects\expapp\capp\cwarppers.cpp(17): error C2227: left of '->sum' must point to class/struct/union/generic type
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

【问题讨论】:

  • 编译器错误日志中的cwarppers.cpp 是什么?您没有显示这样的文件(尽管它似乎拼写错误)。
  • extern "C" 并不意味着它是 C 代码,只是它使用 C ABI 和命名约定。函数体仍然是 C++。

标签: c++ api class wrapper


【解决方案1】:

class Abcstruct Abc_C 类型(在任何地方都没有定义)完全不相关。您在 C 标头中的 typedef 是错误的。它是未定义类型的别名。因此new Abc_C(); 试图创建一个不完整类型的对象。

一个简单的解决方法是按如下方式更改别名:

typedef struct Abc Abc_C;

现在别名是正确类型的名称。

【讨论】:

    猜你喜欢
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 2011-05-11
    • 1970-01-01
    相关资源
    最近更新 更多