Pass a structure as a pointer to function of other type

Hi there,

I have a structure

1
2
3
4
5
6
7
8
9
10
11
  struct A
   {

   public:
      uint16_t c1;

      uint16_t c2;

      uint16_t c3;

   };


And a function

1
2
3
4
void function (uint16_t * data)
{
    // do something
}


I want to pass my structure to the function as a data but the type is different. How could i do this? I cannot change the Parameter type of *data to struct or anthing else. suggestions please
Last edited on
Why? You have to tell more details.
this function is inside the Driver library which takes *data as a pointer to Array. I can pass one element of structure like

 
function (&A.c1);


How to pass the complete structure?
How does that library function know how many elements are in the array?

Note: If A is typename, then you would call:
1
2
3
A foo;
// set foo
function( &foo.c2 );


A naive wrapper:
1
2
3
4
5
6
7
void wrapA( A & foo ) {
  uint16_t bar[] = { foo.c1, foo.c2, foo.c3 };
  function( bar );
  foo.c1 = bar[0];
  foo.c2 = bar[1];
  foo.c3 = bar[2];
}


However,
1
2
3
4
5
6
7
8
union A {
  uint16_t arr[3];
  struct {
    uint16_t c1;
    uint16_t c2;
    uint16_t c3;
  } s;
};

.. but foo.s.c3 is less convenient than foo.c3 of the old A.

Perhaps,
1
2
3
4
5
6
7
struct A {
  uint16_t arr[3];
  uint16_t & c1;
  uint16_t & c2;
  uint16_t & c3;
  A() : c1(arr[0]), c2(arr[1]), c3(arr[2]) {}
};

Also on unions: writing to one field and then reading from other is technically an undefuned behavior. Struct with references or wrapper function is probably the best approach.

(Passing pointer to first element of structure to threat it as array will not work either as compiler can add paddding between members which is forbidden for arrays)
@keskiverto
This is little bit stupid library, it asks for pointer to some data and then increment to that pointer for some fixed numbers, actually.

1
2
3
4
5
6
7
8
void function (uint16_t * data)
{
while(i<9) 
{   
     cout << *data++;
     i++;
}
}

This function's parameter data seems to be pointer to an array with fixed length.
This function's parameter data seems to be pointer to an array with fixed length.

Stupid or not, the description of the function must tell what it requires and what it provides (i.e the interface) and you must pass it the required data.

In other words, if your friend (function) is hungry (needs array of 7 uint16_t), then you should not attempt to shovel a Ferrari (struct A) down his throat.
Topic archived. No new replies allowed.