Re: std::function and shared object libraries

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Gabriel Marcano <gabemarcano@xxxxxxxxx> writes:

> Sadly, I can't realistically null the function pointers in my
> application when unloading the shared libraries (plugins). The
> function objects are actually made by an object in the main
> application when the plugin calls a function to register a
> callback.

Can you instead make the main application (or a permanently
loaded shared object) do the conversion from a function pointer
to std::function?  Then the manager instantiation would not be
unloaded.  I suppose this will be difficult if you're using
operator() rather than function pointers, though.

I added the -Wl,-E option so that the shared object can link to
the assign(std::function<void()>&, void (*)()) symbol defined in
the main program.

------------------------------
Makefile:

CXXFLAGS = -Wall -Wextra -pedantic -std=c++11 -g -O0 -fPIC

.PHONY: clean all

all: test shared.so

test: main.o
	$(CXX) $(CXXFLAGS) -Wl,-E $^ -o $@ -ldl

shared.so: shared.o
	$(CXX) $(CXXFLAGS) $^ -o $@ -fPIC -shared

clean:
	rm -f *.o test shared.so

------------------------------
main.hpp:

#ifndef MAIN_HPP
#define MAIN_HPP

#include <functional>

void assign(std::function<void()>&, void (*)());

#endif

------------------------------
main.cpp:

#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include "main.hpp"

void assign(std::function<void()> &obj, void (*fp)())
{
  obj = fp;
}

int main()
{
  typedef void(*sh_f)(std::function<void()>&);
  void *lib = dlopen("./shared.so", RTLD_NOW);
  if (!lib) {
    fprintf(stderr, "%s\n", dlerror());
    return EXIT_FAILURE;
  }
  sh_f sh = (sh_f)dlsym(lib, "load");
  std::function<void()> f;
  sh(f);
  dlclose(lib);
  return 0;
}

------------------------------
shared.cpp:

#include "main.hpp"

void shared()
{}

extern "C" void load(std::function<void()>& fun)
{
  assign(fun, shared);
}

------------------------------



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux