tags:

views:

91

answers:

3

Sample eg:

messageStruct.hpp

class MessageStructure_t{

public:

struct MsgData_t {

   float a;
   int i;

}__attribute__((packed))msgdata_m;

};//classs end

I have a file in my project Application.c. I need to access the structure variables here. Both are different, one .hpp and the other .c

How can I do this ?

Hoping your kind attention.

+2  A: 

You can define the struct in a separate header fine msg_data.h, and then include it in both projects. If needed you may have to typecaset the MessageStructure_t pointer into MsgData_t.

hence MsgData.h:

struct MsgData_t {
   float a;
   int i;
}__attribute__((packed));

messageStruct.hpp:

#include "MsgData.h"

class MessageStructure_t {
  public:
    MsgData_t msgdata_m;
}

Appliaction.c:

#include "MsgData.h"

//...
Kornel Kisielewicz
but I don't have the permission to change cpp class
This won't be enough since you cannot access the data in the class from C. This would need a free function. However, you cannot simply pass an object of the the class to that function, since C doesn't understand classes...
sbi
how about if I create dt structure's var in c using extern something like:MessageStructure_t::MsgData_t obj_MsgData_t;
m not getting any idea...must i create a wrapper code....
@rejinacm Yes, create wrapper code.
Daniel Daranas
@rejinacm: unfortunately so.
Kornel Kisielewicz
+1  A: 

I think that the best way would be to create an extern "C" function to access the structure.

Ofir
But even this begs the question how to pass a class instance to that method from C.
sbi
@sbi I'm not sure what's so uncertain or mysterious about this. You create `extern "C"` functions which wrap the methods. If need be you can also write a `MessageStructure_Create()` to wrap `new` and the constructor(s), and `MessageStructure_Free()` to wrap `delete`. Not sure what the type should be? Do a `typedef` from `void*`. You can write accessor functions for fields.
asveikau
@asveikau: See http://stackoverflow.com/questions/2138337/how-to-access-a-structure-variable-which-is-inside-a-cpp-class-from-c/2138546#2138546 `:o)`
sbi
+3  A: 

When you want to access C++ classes and their objects from C, there are a few well-known patterns around. Google for them.

An easy one is to wrap it in a piece of OO C:

typedef void* my_handle_t;

handle_t create(void);  // returns address of new'ed object
void destroy(handle_t); // deletes object

MsgData_t* get_data(handle_t); // returns address of data in object

That leaves the question of how to make MsgData_t accessible from C. I see three possibilities:

  1. move its definition into its own header (IMO best, but you already said you're not allowed to do it)
  2. duplicate its definition (easy, but IMO worst alternative)
  3. fiddle with the preprocessor (#ifndef __cplusplus) to make the C++ header accessible for a C parser (hackish, but avoids the code duplication of #2)
sbi