Accessing inherited std.vector<std.string> field causes EXC_BAD_ACCESS

I have a struct in cpp that holds a std.vector of std.strings. Accessing that field on a child in swift causes EXC_BAD_ACCESS after the second access.

I think it might be connected to Accessing a std.string on a base cpp class frees the string prematurely · Issue #76650 · swiftlang/swift · GitHub . They might have common cause, but I’m not that well versed in how it all works under the hood. But the behaviour and error messages are the same…

minimal test case:
in cxx target:

namespace cxx_test{
struct parent_struct{
	int64_t a;
	std::string c;
	std::vector<int64_t> v1;
	
	parent_struct(const std::string& c){
		this->c = c;
		this->a = 0;
		this->v1 = std::vector<int64_t>();
	}
};

struct child1:public parent_struct{
	child1():parent_struct("child1"){
		a = 1;
	}
};

static child1 getchildobj1(){
	auto x = child1();
	x.v1.resize(2, 32);
	return x;
}
}

and in swift:

import cxxtarg

@main
struct test{
  public static func main(){
	  let x = cxx_test.getchildobj1()
	  for i in x.v1{
		  print(i)
	  }

  }
}

Again, it can be worked around by passing the instance to a cpp function that will return the vector in question… but like with accessing strings inherited from parent, it’s a clunky workaround.

1 Like