如何在C中使用vector <struct>输出参数包装C ++函数?

时间:2019-06-10 22:47:46

标签: c++ c pointers wrapper opaque-pointers

我正在编写C包装程序,需要从struct向量中获取数据。

要包装的结构和函数

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);

我在C语言中重新定义了foo struct,但是如果我应该使用opca类型作为句柄,则可能不是必需的。 标头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);

使用此代码,当我读取foo_wrapper指针时,在main.c中出现运行时指针错误。 munmap_chunk(): invalid pointer

0 个答案:

没有答案