I'm coding a C wrapper and need to get data from a vector of struct.
struct and functio to wrap
struct foo {
string name;
time_t datetime;
string uid;
int number_id;
string store;
string city;
invoice():number_uid{INT_MAX}{}
};
struct bar {
int foo;
string name;
}
int cpp_function(vector<struct foo> &some_foo);
I redefined foo struct in C, but maybe is not necesary if I should use an opca type as handle. Header wrapper.h
#ifdef __cplusplus
extern "C" {
#endif
struct foo {
char *name;
time_t datetime;
char *uid;
int number_id;
char *store;
char *city;
};
typedef struct foo_wrapper foo_wrapper;
struct bar_wrapper {
int foo;
char *name;
}
typedef struct bar_wrapper bar_wrapper;
bar_wrapper *c_function_create(foo_wrapper **foo_wrapper, int *number_foo);
#ifdef __cplusplus
}
#endif
wrapper.cpp
extern "C" struct bar_wrapper {
struct bar instance;
};
bar_wrapper *c_function_create(foo_wrapper **foo_wrapper, int *number_foo)
{
bar_wrapper *bar_wrapper = new bar_wrapper;
struct bar& bar = bar_wrapper->instance; //<-- note the reference
vector<struct foo> some_foo;
int ret = cpp_function(&some_foo);
*foo_wrapper = (foo_wrapper*)malloc(sizeof(**foo_wrapper));
*number_foo = some_foo.size();
// How to write a some_foo.size() structs into the foo_wrapper pointer to structs?
// Below code is not correct
for (i=0; i<some_foo.size(); i++)
{
(*foo_wrapper + (i * sizeof(foo_wrapper)))->name = some_foo[i].name;
(*foo_wrapper + (i * sizeof(foo_wrapper)))->datetime = some_foo[i].datetime;
(*foo_wrapper + (i * sizeof(foo_wrapper)))->uid = some_foo[i].uid;
(*foo_wrapper + (i * sizeof(foo_wrapper)))->number_id = some_foo[i].number_id;
(*foo_wrapper + (i * sizeof(foo_wrapper)))->store = some_foo[i].store;
(*foo_wrapper + (i * sizeof(foo_wrapper)))->city = some_foo[i].city;
}
return bar_wrapper;
}
main.c
foo_wrapper *foo_wrapper;
int number_foo = 0;
int ret = c_function_create(&foo_wrapper, &number_foo);
With this code I'm getting runtime pointer errors, in main.c
when I read a foo_wrapper pointer.
munmap_chunk(): invalid pointer