Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pointer function to other class function

I need help with passing a function pointer on C++. I can't linkage one function for a class to other function. I will explain. Anyway I will put a code resume of my program, it is much larger than the code expose here but for more easier I put only the part I need to it works fine.

I have one class (MainSystem) and inside I have an object pointer to the other class (ComCamera). The last class is a SocketServer, and I want when the socket received any data, it sends to the linkage function to MainSystem.

ComCamera is a resource Shared with more class and I need to associate the functions ComCamera::vRecvData to a MainSystem::vRecvData or other function of other class for the call when receive data and send de data to the function class associate.

Can Anyone help to me?

EDDITED - SOLUTION BELOW

main.cpp

#include <iostream>
#include <thread>  
#include <string>
#include <vector>
#include <cmath>
#include <string.h>
#include <stdio.h>
#include <exception>
#include <unistd.h>

using std::string;

class ComCamera {
public:
    std::function<void(int, std::string)> vRecvData;

    void vLinkRecvFunction(std::function<void(int, std::string)> vCallBack) {
        this->vRecvData = vCallBack;
    }

    void vCallFromCamera() {
        this->vRecvData(4, "Example");
    };
};

class MainSystem {
private:
    ComCamera *xComCamera;
public:
    MainSystem(ComCamera *xComCamera) {
        this->xComCamera = xComCamera;
        this->xComCamera->vLinkRecvFunction([this](int iChannelNumber, std::string sData) {vRecvData(iChannelNumber, sData); });
    }

    void vRecvData(int iNumber, string sData) {
        std::cout << "RECV Data From Camera(" + std::to_string(iNumber) + "): " << sData << std::endl;
    };
};

int main(void) {
    ComCamera xComCamera;
    MainSystem xMainSystem(&xComCamera);

    xComCamera.vCallFromCamera();

    return 0;
}

Output will be:

MainSystem RECV Data From Camera(4): Example

like image 475
Redhunt Avatar asked Aug 05 '26 15:08

Redhunt


1 Answers

You can have ComCamera::vRecvData be of type std::function<void(int, std::string)> and then have ComCamera::vLinkRecvFunction() be like this:

void ComCamera::vLinkRecvFunction(std::function<void(int, std::string)> callBack)
{
    this->vRecvData = callBack;
}

and have MainSystem constructor be like this:

MainSystem::MainSystem(ComCamera *xComCamera)
{
    using namespace std::placeholders;

    this->xComCamera = xComCamera;
    this->xComCamera->vLinkRecvFunction([this](int iNumber, std::string sData){vRecvData(number, sData);});
}

Still though the original question has way too much code to go through friend.

like image 50
Geezer Avatar answered Aug 08 '26 09:08

Geezer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!