Não sei em qual momento ocorreu o erro de memória que você falou, mas provavelmente foi na sua chamada à dlopen()
Vamos dar uma breve olhada no manual de dlopen() (traduzi apenas o relevante)
user@host:~$ man 3 dlopen
:
ORIGINAL
...
One of the following two values must be included in flags:
RTLD_LAZY:
Perform lazy binding. Only resolve symbols as the code that references them is executed. If the symbol is never referenced, then it is never resolved. (Lazy binding is performed only for function references; references to variables are always immediately bound when the shared object is loaded.) Since glibc 2.1.1, this flag is overridden by the effect of the LD_BIND_NOW environment variable.
RTLD_NOW:
If this value is specified, or the environment variable
LD_BIND_NOW is set to a nonempty string, all undefined symbols
in the shared object are resolved before dlopen() returns. If
this cannot be done, an error is returned.
TRADUZIDO
* Está muito mais para um resumo do que uma tradução :-)
...
Um dos dois valores abaixo precisa ser incluido em flags:
RTLD_LAZY:
Somente resolve os symbols quando o código que referencia (faz referência à) estes é executado.
RTLD_NOW:
Todos os symbols não-definidos (como um protótipo de função veja este link) no shared object são resolvidos antes que dlopen() retorne.
Como podemos ver, você precisa incluir um desses dois valores acima nas flags do dlopen()
void *dlopen( const char *filename, int
flags
);
A flag RTLD_GLOBAL que usou é opcional e no seu caso não é necessária.
O código ...
Alterei alguns nomes para
facilitar o entendimento. O código está comentado.
main.c user@host:~$ gcc -ldl -o main main.c
#include <dlfcn.h>
int
main (int argc, char **argv) {
void *handle;
void (*function)();
int x = 10;
/* vamos abrir a shared library com dlopen(..., RTLD_NOW)
* -> RTLD_GLOBAL não é necessário porque você não vai "abrir" um
* symbol desta shared library em outra shared library */
handle = dlopen("./shared.so", RTLD_NOW);
function = dlsym(handle, "print");
function(&x);
/* temos que fechar a shared library :-) */
dlclose(handle);
return 0;
}
shared.c user@host:~$ gcc -shared -o shared.so shared.c
#include <stdio.h>
void
print (int *i) {
printf("%d\n", *i);
}
read(&x)
? Vc checou se o ponteiro tem um valor válido quando retorna da chamada dedlsym(handle, "check");
? (afinal, se houver um erro na definição do símbolo, essa função retorna nulo) Edite a questão e adicione os detalhes, senão fica difícil alguém te ajudar.printf
dentro decheck
, se eu deixarprintf("%d\n", *i);
ele escreve o mesmo valor que estará no main, mas quando eu uso o*
, da erro de acesso de memória inválido*
"?