首页 > 解决方案 > How to give a instance a function from a library in C?

问题描述

I wanted to give the aRest library a function to expose to the api. But I am importing a customlibrary, I wanted to give the aRest instance a function in that library. This is my code

#include <ESP8266mDNS.h>
#include <ESP8266WiFi.h>
#include <aREST.h>
#include <EEPROM.h>
#include <WiFiClient.h>


//My Custom Made C/C++ Libraries
#include <DeviceEeprom.h>
#include <DeviceRoute.h>

//Creating my customLib instances
DeviceEeprom deviceEeprom   = DeviceEeprom();
DeviceRoute deviceRoute     = DeviceRoute();

// Create aREST instance
aREST rest = aREST();

int myFunction();


void setup()
{
 Serial.begin(115200);
 rest.set_id("1");
 rest.set_name("esp8266");
 rest.function("myFunction" &myFunction);
}

void loop()
{

}

int myFunction()
{
 return 1;
}

I wanted to go from this.

rest.set_function("myFunction" &myFunction);

To this.

rest.set_function("myFunction" deviceRoute.myFunction());

UPDATE

I found the rest.function() code This is the code

void function(char * function_name, int (*f)(String)){

  functions_names[functions_index] = function_name;
  functions[functions_index] = f;
  functions_index++;
}

Mayby this helps out?

标签: c++

解决方案


无法将指向非静态成员函数的指针直接传递给aREST::function.

非静态成员函数不同于静态成员函数和独立函数。他们需要一个对象来处理。这意味着&DeviceRoute::myFunction与 type 不兼容int(*)(String)。相反,它是一个int (DeviceRoute::*)(String).

要完成这项工作,您需要一个静态或独立的包装函数来调用您想要的成员函数。由于aREST::function不接受任何类型的上下文指针,您唯一真正的选择是使用全局变量:

//Creating my customLib instances
DeviceEeprom deviceEeprom;
DeviceRoute deviceRoute;

// Create aREST instance
aREST rest;

int myFunction(String s)
{
    return deviceRoute.myFunction(s);
}

void setup()
{
 Serial.begin(115200);
 rest.set_id("1");
 rest.set_name("esp8266");
 rest.function("myFunction" &myFunction);
}

void loop()
{

}

推荐阅读