Page 1 of 1

Calling a C++ class-method

Posted: Sat Nov 02, 2019 7:52 pm
by dasarne
Hello, everybody,
I want to call a method in a C++ class from an event in ESP-IDF in an xTask.
Here is the class and method „dispatch“ I want to call:

Code: Display.h Select all

/*
* Display.h
*
* Created on: 01.11.2019
* Author: arne
*/

#ifndef COMPONENTS_HARDWARE_DISPLAY_H_
#define COMPONENTS_HARDWARE_DISPLAY_H_

#include "Modell.h"

class Display {
public:
Display();
virtual ~Display();
/**Analysiert die Befehle des Frontends und ruft entsprechende Methoden auf*/
void dispatch(char *str);
private:
Modell theModell;
};

#endif

Code: Display.cpp Select all

/*
* Display.cpp
*
* Created on: 01.11.2019
* Author: arne
*/

#include <Display.h>

Display::Display() {
// TODO Auto-generated constructor stub

}

Display::~Display() {
// TODO Auto-generated destructor stub
}

void Display::dispatch(char *str) {

}
To encapsulate the method in an external "C" method I wrote the following wrapper:

Code: DisplayC-Wrapper.h Select all

/*
* DisplayC-Wrapper.h
*
* Created on: 01.11.2019
* Author: arne
*/

#ifndef COMPONENTS_HARDWARE_DISPLAYC_WRAPPER_H_
#define COMPONENTS_HARDWARE_DISPLAYC_WRAPPER_H_

#ifdef __cpluscplus
class Display;
extern "C" {
#else
struct Display;
typedef struct Display Display;
#endif
Display *Display_new();

void Display_dispatch(Display *instance, char *str);

#ifdef __cpluscplus
}
#endif
#endif
Here is the implementation of the wrapper:

Code: DisplayC-Wrapper.c Select all

/*
* DisplayC-Wrapper.c
*
* Created on: 01.11.2019
* Author: arne
*/

#include "DisplayC-Wrapper.h"
#include "Display.h"

Display *Display_new()
{
return new Display();
}

void Display_dispatch(Display *instance, char *str)
{
instance->dispatch(str);
}
And here the corresponding call in the xTask:

Code: display.c Select all

void rx_task() {
Display *instance = Display_new();
Display_dispatch(instance,"Test");
}
Everything compiles but doesn't link.
I got the following error-message at linkage time:

What do I have to do to make this linking?
Are there suitable compiler flags?
Is it possible to address C++ classes from C methods at all?
Is there more information about this topic somewhere? The best would be to find a working example...

Many greetings
Arne

Re: Calling a C++ class-method

Posted: Sun Nov 03, 2019 11:26 am
by PeterR
Passing the class instance around as 'void *' and then casting is the usual trick.
If the class member dispatch is static then you can just pass the member address as a function pointer.

Code: Select all

extern "C" CToCPlusPlus(void *displayPtr, const chat *str) {
   ((Display *)displayPtr)->dispatch(str);
}