0

I have a C++ file which is like below:

int myNum[10] = {10, 20, 20, 40, 50, 60, 70, 80, 90, 100};

struct rfid
{
    int AntennaID;
    char *tid;
};

for (int i = 0; i < 10; i++) {
    AntennaID = myNum[i];

    struct rfid p1 = {AntennaID, tid};

    cout << "roll no : " << p1.AntennaID << endl;
    cout << "roll no : " << p1.tid << endl; 
    passInfo(*p1);
}

And I have a C file, which is like below:

#include <stdio.h>

void passInfo(*p1)
{
    printf("%s :: \n", *p1);
}

How to pass the structure which is framed in C++ to a function of C?

7
  • passInfo is a function which is in c file. Have used extern c to in c++ file to access the function. Commented Jun 17, 2020 at 6:48
  • 2
    void passInfo(*p1) does this even compile? you did not specify type of *p1 Commented Jun 17, 2020 at 6:49
  • No, its not. I dont know, how to achieve my result for this. I am not aware of c & c++ functionalities. Commented Jun 17, 2020 at 6:51
  • The question is unclear. You have a .cpp file and a .h file ? or .cpp and .c? What compiler? Commented Jun 17, 2020 at 6:53
  • 1
    what should this be? void passInfo(*p1) Commented Jun 17, 2020 at 7:07

1 Answer 1

1
  1. Make a header that will compile for both C and C++.
// shared.h
typedef struct rfid_
{
    int AntennaID;
    char *tid;
} rfid;

#if defined __cplusplus
extern "C"
#endif
void passInfo(rfid *p1);
  1. Implement your function in C.
// c.c
#include <stdio.h>
#include "shared.h"

void passInfo(rfid *p1) 
{
    // whatever you want
}
  1. Use your function in C++ by including the header.
// cpp.cpp
#include <iostream>
#include "shared.h"

int test()
{
    int myNum[10] = {10, 20, 20, 40, 50, 60, 70, 80, 90, 100};

    for (int i = 0; i < 10; i++) {
        AntennaID = myNum[i];
        rfid p1 = {AntennaID, tid};
        cout << "roll no : " << p1.AntennaID << endl;
        cout << "roll no : " << p1.tid << endl;
        passInfo(&p1);
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

In c.c, void passInfo(rfid *p1) needs to be void passInfo(struct rfid *p1). The code would be cleaner if shared.h defined typedef struct rfid rfid; under C, instead of using 2 #ifs on the passInfo() declaration.
#if !defined __cplusplus struct #endif is not needed.
@RemyLebeau I will modify the answer.
@KamilCuk yes, it is. Under C, struct type names must always be prefixed with struct. That is not needed in C++.
Not needed, but if you write it, nothing happens ; ) I meant just to leave void passInfo(struct rfid *p1). I meant the #if !defined __cplusplus and #endf are not needed around struct.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.