Using cgo with cpp vector

Hello.
I guess this is a c++ issue, but I don’t know where to post my question, so here it is.

I’m trying to use a vector in a cgo binding, but the first index of output always show weird data like below.
structs is cgo binary and company.exe is cpp binary.

$ ./structs
# Inside function where vector declared
  0: wlrbbmqb, $6421.00
  1: darzowk, $9172.00
  2: hiddqs, $7862.00
  3: xrjmowfr, $6393.00
  4: jybldb, $8784.00
# Outside function where vector declared
#### Employee list:
  0: , $6421.00
  1: darzowk, $9172.00
  2: hiddqs, $7862.00
  3: xrjmowfr, $6393.00
  4: jybldb, $8784.00

$ ./company.exe 
# Inside function where vector declared
  0: wlrbbmqb, $6421.00
  1: darzowk, $9172.00
  2: hiddqs, $7862.00
  3: xrjmowfr, $6393.00
  4: jybldb, $8784.00
# Outside function where vector declared
#### Employee list:
  0: , $6421.00
  1: darzowk, $9172.00
  2: hiddqs, $7862.00
  3: xrjmowfr, $6393.00
  4: jybldb, $8784.00

I tried both msvc 2022 / mingw gcc 12.2.0 on windows 11 and gcc 9.4.0 on ubuntu 20.04.
Is there something that I lost or wrong?

Any hint is welcome.

The source is here.

Apologies for my poor English.

Hi, @edp1096 and welcome to the forum!

I am not a C++ programmer, so I may be wrong here, but I think this might be related to the vector itself going out of scope at the end of generate_employee_list_vector at which point the vector (and its backing array) are destroyed, so when you use emp_list later, I think you’re experiencing undefined behavior. I see you have a second version that uses malloc; are you seeing the same thing there?

Thank you for answer, @skillian .

Perhaps yes, I tried also emp_list_malloc as your mention and it works well.

Although the function generate_employee_list_vector don’t work, I guessed, below redeclaration would keep the values from vector destuction.

void generate_employee_list_vector(void* cmp, int count) {
....
    c->emp_list = new employee_list{emp_list.data(), emp_list.size(), false};
}

My wondering is, this due to my immature code or a C++ compiler issue.

No, there is no transfer of ownership of the array from the vector to your employee_list. The data member function returns an “unowned” pointer that can be used while the vector exists. There is no way that I am aware of to move the vector’s backing array out of the vector.

I would recommend putting the vector into the company so that its lifetime is preserved as long as the company exists. I submitted a pull request with the changes that I would suggest if you want to use the vector. I am not 100% certain that I got it right, but it did work for me.

1 Like

Thank you @skillian , your code is very helpful to me!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.