From my understanding C assumes all parameters are int's and it returns ints. I'd like to pass around this object but i have no idea how and AFAIK its the same size of int but it breaks. Here is the Reproducible code.
In testc.c. Note: this MUST be in a C file.
int test_c1() {
return test_c3(test_c2());
}
In testcpp.cpp
#include <iostream>
using namespace std;
struct MyType{
int a, b;
};
template <class T>
struct WrappedPointer {
T* lhs;
public:
void LHS(T*v) { lhs=v; }
T* LHS() { return lhs; }
WrappedPointer(){}
WrappedPointer(T*value) : lhs(value){}
WrappedPointer(const WrappedPointer&v) : lhs(v.lhs){}
T* operator->() const { return lhs; }
T* operator*() const { return lhs; }
};
typedef WrappedPointer<MyType> ObjPtr;
static_assert(sizeof(ObjPtr) == sizeof(int), "");
static_assert(sizeof(ObjPtr) == sizeof(void*),"");
extern "C" {
ObjPtr test_c1();
ObjPtr test_c2() {
//ObjPtr s=0;
ObjPtr s;
s.LHS(0);
cout <<"c2 " << s.LHS() << endl;
return s;
}
ObjPtr test_c3(ObjPtr v) {
cout <<"c3 " << v.LHS() << endl;
return v;
}
};
int main() {
auto v = test_c1();
cout <<"main " << v.LHS() << endl;
}
gcc compile flags
gcc -Wall -c testc.c
testc.c: In function 'test_c1':
testc.c:2:2: warning: implicit declaration of function 'test_c3' [-Wimplicit-function-declaration]
testc.c:2:2: warning: implicit declaration of function 'test_c2' [-Wimplicit-function-declaration]
g++ -std=c++0x -Wall -c testcpp.cpp
g++ testc.o testcpp.o
a.exe
It should crash and as you can see the only warning i ever got was the function is implicit :(. Why does a crash? especially when i asserted that ObjPtr
is indeed the same size as int. How do i fix this so that i can pass around ObjPtr? I CAN NOT modify the C library so testc.c is off limits.
-edit- instead of crashing in VS 2010 i get this printout which shows the passed object is incorrect. I don't understand where "B" comes from at the end. This happens in debug mode. Release crashes with access violation.
c2 00000000
c3 0046F8B0
main CCCCCCCC
B
Press any key to continue . . .
If your curious, if you comment out the constructors (and change nothing else) this will work in gcc. If you change class into struct so no member is private it will work in msvc2010. This fix is nonsense but it appears its consider POD when i do this and magically the code works. Which is weird since the definition in C hasn't changed (as there is no definition). And the constructors aren't doing anything different.