Calling an external C function (in a shared lib) from Perl with Inline/C does not work

Viewed 350

The code is more or less stolen from the page of the author: https://metacpan.org/pod/distribution/Inline-C/lib/Inline/C/Cookbook.pod but does not give the expected results:

use Inline C => Config =>
           enable => autowrap =>
           LIBS => "-lmylib ";
use Inline C => <<'END_OF_C_CODE';

extern char *sharedFun(char *);

void greet(char* name) {
  printf("Hello %s!\n", name);
}


char *func(char* name) {
  static char mystr[1024];
  char *p;

  strcpy(mystr, "string: ");
  p = sharedFun(name);
  strcpy(mystr, p);

  return(mystr);
}

END_OF_C_CODE

greet('Hello World');
greet(42);
$p = func("foobar");
print $p, "\n";

The result of the execution is:

nm libmylib.so | grep shared
000000000000056a T sharedFun
file libmylib.so
libmylib.so: ELF 64-bit LSB shared object, x86-64, version 1 (FreeBSD), dynamically linked, not stripped


$ perl inline.pl
Hello Hello World!
Hello 42!
/usr/home/guru/Perl/_Inline/lib/auto/inline_pl_9404/inline_pl_9404.so: Undefined symbol "sharedFun"

and I checked with strace: the shared lib libmylib.so is not searched for. Why?

2 Answers

I think the lib is searched for but isn't found and therefore the symbols aren't loaded.

From the documentation you may be able to provide the path to the library: LIBS => '-L/your/lib/path -lyourlib';

I figured out what the problem is: The required shared lib must exist in the first run of perl inline.pl (when the connectors get compiled). If it is not there, later it is never search for:

$ perl inline.pl
Hello Hello World!
Hello 42!
/usr/home/guru/Perl/_Inline/lib/auto/inline_pl_8196/inline_pl_8196.so: Undefined symbol "sharedFun"
$ clang -shared -o libmylib.so mylib.c
$ ls -l libmylib.so
-rwxr-xr-x  1 guru  wheel  5546  4 nov.  22:23 libmylib.so
$ perl inline.pl
Hello Hello World!
Hello 42!
/usr/home/guru/Perl/_Inline/lib/auto/inline_pl_8196/inline_pl_8196.so: Undefined symbol "sharedFun"


$ rm -r _Inline
$ perl inline.pl
Hello Hello World!
Hello 42!
foobar

We can close this thread.

Related