• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 253
  • Last Modified:

Managed function pointers

OK, this is my case:

I have one class library that recieves network data, and interprets that very data. When a command reaches the interpreter, I want a function in another class library to be executed when a specific command is executed.

The class library which holds the function that should be executed already holds a reference to the network library, so adding the class library holding the function to be executed can not be referenced from the network library.

I would therefore need function pointers I guess.

My problem is that I don't know how I would create these pointers, is delegates the correct way?

Unmanaged function pointers just doesn't seem to work in managed C++.

Any help is appreciated!
0
bjqrn
Asked:
bjqrn
1 Solution
 
AlexFMCommented:
I hope this sample can help:

using namespace System;

public delegate int FunctionPtr(int);

ref class Server
{
public:
    int Function(int n)
    {
        return n + 1;
    }

    static int StaticFunction(int n)
    {
        return n - 1;
    }
};

ref class Client
{
public:
    void DoSomething(FunctionPtr^ ptr, int n)
    {
        int result = ptr(n);
        Console::WriteLine(result.ToString());
    }
};

int main(array<System::String ^> ^args)
{
    Server^ server = gcnew Server();
    Client^ client = gcnew Client();

    FunctionPtr^ ptr = gcnew FunctionPtr(server, &Server::Function);
    client->DoSomething(ptr, 1);

    ptr = gcnew FunctionPtr(&Server::StaticFunction);
    client->DoSomething(ptr, 10);

    return 0;
}
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now