Reputation: 343
I need to call an API function which needs a struct-pointer as a parameter.
lets say its this struct
struct SomeObject{
double a;
double b;
}
and this function to call: func(SomeObject*)
The problem here is that I only have access to data as a custom struct but the same structure like SomeObject given as an vector.
struct CustomObject{
double a;
double b;
}
And the compiler is throwing errors because they are different parameters. cannot convert 'std::vector<CustomObject>' to 'SomeObect*' in argument passing
. I tried already to pass the CustomObject as a pointer but its of course still a different Object.
Is there any chance to get this working what I am trying to do? And what could be a possible approach?
Upvotes: 0
Views: 1366
Reputation: 68033
reinterpret_cast
might have 'solved' the problem, but has made your code incredibly brittle. I'd really not recommend that approach.
Instead I'd manually construct a SomeObject
from the CustomObject
:
SomeObject x;
x.a = myCustomObj.a;
x.b = myCustomObj.b;
func(&x);
This also avoids the const
issue. Don't even think about optimizations or efficiency at this stage. YAGNI.
Upvotes: 1
Reputation: 238311
You can't pass a std::vector
to a function that expects a pointer. If the function expects a pointer to an array, then you can get that pointer using std::vector::data
Now, that leaves us with the problem that the vector contains objects of a wrong type. The pointer returned by std::vector::data
will be of type CustomObject*
while you need SomeObject*
. They're unrelated, but identical types and luckily, standard layout types. As long as those two requirements hold, that gives us the guarantee that the types have the same representation. Therefore, we can simply cast the pointer with reinterpret_cast:
func(reinterpret_cast<SomeObject *>(vec.data()));
The compiler is now showing 'cast away qualifiers'. It seems to have a problem with because CustomObject is currently a const.
I take that to mean that the vector is const
, or it's a vector of const
objects. In that case you shouldn't pass it's data to a function that takes a pointer to non-const
. But if you know that the function will not modify the objects, despite taking a pointer to non-const, and you want to get rid of the compiler warning, then you must cast the constness away explicitly, using const_cast.
Upvotes: 4