C++ using a library in C

In my C++ program, I need to use a data structure defined in a C library that I cannot modify. I will explain my question will a simplified example:

In test.h, a struct L1 is defined, with nested structures L2 and L3.
========== test.h BEGIN ===========
struct L1 {
int element;
struct L2 {
int element;
struct L3 {
int element;
} *L3;
} *L2;
};
========== test.h END =============

I think, the way that the data structure is defined is a bit nasty, but I simply cannot correct it. Now if I am using C, I will be able to define variables like
struct L2 *l2;
struct L3 *l3;

In C++, I tried various different methods, but I still cannot define a pointer to struct L2. The following is an attempt which does not compile. Any tips will be appreciated. Thanks a lot!

=============== test.cpp BEGIN ================
#include <iostream>
#include "test.h"

void function1(L1 *l1) {
std::cout<< l1->element << std::endl;
}

void function3(L1::L2::L3 *l3) {
std::cout<< l3->element << std::endl;
}

int main(int argc, char **argv) {

L1 *l1;
L1::L2 *l2;
L1::L2::L3 *l3;
l1 = new L1;
l1->element = 1;
l2 = new L1::L2;
l2->element = 2;
l3 = new L1::L2::L3;
l3->element = 3;
l2->L3 = l3;
l1->L2 = l2;
function1(l1);
function3(l1->L2->L3);
}
=============== test.cpp END ==================

Actually struct L2 is a data member of struct L1. struct L3 is a data member of struct L2.

Below code works and you can access pointer to struct L2 and struct L3. Compile using g++ instead of gcc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main() {

struct L1 {
  int element;
  struct L2 {
    int element;
    struct L3 {
      int element;
    } *L3;
  } *L2;
};

struct L1 *l1;
struct L1::L2 *l2 = l1->L2;
struct L1::L2::L3 *l3 = l2->L3;

return 0;
}
sohguannh, thanks a lot.

Seems that your solution works. But now if I define the variables in the way you suggested, and use these variables to call the C-functions in the library, I will get error like:

test.cpp:34: error: cannot convert ‘L1::L2::L3*’ to ‘L3*’ for argument ‘1’ to ‘void cfunction3(L3*)’

the C-library was compiled by gcc. The C++ file is compiled by g++. The function prototypes for the C-library are properly enclosed in
extern "C" { ...... }

Any idea?

Thanks.
declare struct L2 and struct L3 in your code.
1
2
struct L2;
struct L3;

Actually I'm not getting the error you described. I can compile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
extern "C" {
struct L1 {
int element;
struct L2 {
int element;
struct L3 {
int element;
} *L3;
} *L2;
};
}
int main(){
	struct L2 * l;//this is fine
}

just fine.
Last edited on
Topic archived. No new replies allowed.