开发者

How to access a structure variable which is inside a cpp class,from c?

开发者 https://www.devze.com 2022-12-17 08:35 出处:网络
Sample eg: messageStruct.hpp class MessageStructure_t{ public: struct MsgData_t { float a; int i; }__attribute__((packed))msgdata_m;

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 differen开发者_StackOverflow社区t, one .hpp and the other .c

How can I do this ?

Hoping your kind attention.


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"

//...


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)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消