C ++类的C包装器无法正常工作

时间:2017-09-04 12:26:43

标签: c++ api class wrapper

我是一个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 ==========

1 个答案:

答案 0 :(得分:2)

类型class Abcstruct Abc_C(无处定义)完全不相关。你在C头中的typedef是错误的。它是未定义的类型的别名。因此new Abc_C();正在尝试创建不完整类型的对象。

一个简单的解决方法是更改​​别名,如下所示:

typedef struct Abc Abc_C;

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

相关问题