2

assuming there is a C++ class defined as follow,

/* goo.h */
#ifdef __cplusplus
class goo{
public:
    vector<int> a;
    vector<int> b;
    void calc();
};
#else
typedef struct goo goo;
#endif

#ifdef __cplusplus
extern "C" {

#if defined(__STDC__) || defined(__cplusplus)
void goo_calc(goo *);
#endif

#ifdef __cplusplus
}
#endif

then i want to implement goo::calc() in C, so i write following codes.

/* goo_cpp.cpp */
#include "goo.h"
void goo::calc(){
    goo_calc(this);
}

/* goo_c.c */
#include "goo.h"
void goo_calc(goo *g){
    /* do something with g->a and g->b */
}

but gcc says goo has no fields named a and b, so what's wrong?


UPDATE:

Supposing vector<int> a is replaced by int a[3], and vector<int> b is replaced by int b[3].

Is this correct to access goo->a and goo->b from C function?

Ruby Sapphire
  • 325
  • 3
  • 4
  • 9

1 Answers1

5

You need to implement goo_calc in a C++ translation unit, with C language linkage.

// goo_cpp.cpp
extern "C" void goo_calc(goo *g){
    /* do something with g->a and g->b */
}

No other way to use a C++ type other than in a C++ translation unit.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458