I have a question about returning pointers to C++ objects from C wrappers.
Here are two C++ classes A and B. I essentially want to create an instance of A from B.
class A {
private:
int a;
public:
explicit A(int a) : a(a) {};
int getA() const {
return a;
}
void setA(int a) {
A::a = a;
}
};
class B {
private:
int b;
public:
explicit B(int b) : b(b) {};
int getB() const {
return b;
}
void setB(int b) {
B::b = b;
}
A createA() {
return A(getB()); // A will be a complicated object that must be created from B
}
};
And the C wrapper
extern "C" {
int A_get_a(A *a) {
return a->getA();
}
A *B_getA_1(B *b) {
A a = b->createA();
A *a_ptr = &a;
return a_ptr;
}
void B_getA_2(B *b, A* a_ptr) {
A a = b->createA();
a_ptr = &a;
}
}
In B_getA_1 the static analyzer is complaining that
Address of local variable may escape the function.
Presumably because of the scoping issue. In B_getA_2 however, when using the function via:
int main() {
B b(4);
A* a;
B_getA_2(&b, a); // <--
return 0;
};
the static analyzer complains
Variable 'a' is uninitialized when used here
So, what would be a good way to create an instance of A from B?