简体   繁体   中英

how to access C++ class data member from C function

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM