Rodney Price
Rodney Price

Reputation: 221

python ctypes can't see symbol in shared library

I can see a symbol fact in a shared library:

> nm -D libtest.so
                 w __cxa_finalize
000000000000111a T fact
                 w __gmon_start__
                 w _ITM_deregisterTMCloneTable
                 w _ITM_registerTMCloneTable

but when I do

>>> import ctypes
>>> lib = ctypes.CDLL('./libtest.so')
>>> lib.fact

I get

AttributeError: ./libtest.so: undefined symbol: fact

Here's the content of my test.c file:

int fact(int n);
int fact(int n) {
  if (n <= 0)
    return 1;
  return n*fact(n-1);
}

I compile the shared library using

> gcc -c -fPIC test.c -o test.o
> gcc -shared -o libtest.so test.o

I'm stumped. What am I doing wrong?

Upvotes: 2

Views: 1933

Answers (1)

paxdiablo
paxdiablo

Reputation: 881473

Not sure exactly where your problem lies since it works fine for me :-)

Suggest you try the steps in the following transcript exactly to see if there's an issue (pax$ is my prompt, not part of the commands, and you'll see I'm explicitly using ./ for files to ensure no possibility that it will use files elsewhere in your various search paths):

pax$ cat ./test.c
int fact(int n) { return (n <= 0) ? 1 : n * fact(n-1); }

pax$ gcc -c -fPIC ./test.c -o ./test.o
pax$ gcc -shared -o ./libtest.so ./test.o
pax$ nm -D ./libtest.so
0000000000201028 B __bss_start
                 w __cxa_finalize
0000000000201028 D _edata
0000000000201030 B _end
0000000000000680 T fact
00000000000006ac T _fini
                 w __gmon_start__
0000000000000528 T _init
                 w _ITM_deregisterTMCloneTable
                 w _ITM_registerTMCloneTable
                 w _Jv_RegisterClasses

pax$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import ctypes
>>> lib = ctypes.CDLL('./libtest.so') ; lib
<CDLL './libtest.so', handle 1131fe0 at 0x7fd4c53cf978>

>>> lib.fact
<_FuncPtr object at 0x7fd4c550de58>

>>> lib.fact(6)
720

Upvotes: 2

Related Questions