tags:

views:

171

answers:

1

I'm using the example in python's 2.6 docs to begin a foray into embedding some python in C. The example C-code does not allow me to execute the following 1 line script:

import math

Using line: ./tmp.exe tmp foo bar

it complains

Traceback (most recent call last):
  File "/home/rbroger1/scripts/tmp.py", line 1, in <module>
    import math
ImportError: [...]/python/2.6.2/lib/python2.6/lib-dynload/math.so: undefined symbol: PyInt_FromLong

When I do 'nm' on my generated binary (tmp.exe) it shows

0000000000420d30 T PyInt_FromLong

The function seems to be defined, so why can't the shared object find the function?

The folks at bacula seem to be in the same boat, but I don't understand why.

+2  A: 

I'm using Python 2.6, and I successfully compiled and ran that same example code that you listed, without changing anything in the source.

$ gcc python.c -I/usr/include/python2.6/ /usr/lib/libpython2.6.so
$ ./a.out random randint 1 100
Result of call: 39
$ ./a.out random randint 1 100
Result of call: 57

I specifically chose the random module because it does have from math import log,... so it is certainly importing the math module as well.

Your issue is probably due to how you're linking; see this forum post for a similar issue someone else had. I can't find the links again, but it seems like there are some common issues when trying to link against Python's static library then importing modules that require a dynamic library.

Mark Rushakoff
To follow on from this, you are almost certainly not linking against the Python library correctly. The dynamic linker is trying to resolve that symbol and can't find it in any of your linked libraries. Static linkage quite often doesn't leave the symbols in place for the dynamic linker to resolve so in this case it's best to link dynamically.
Benno
Can I impose upon you two to answer the sequel to this question? Unfortunately, my python install seems incomplete and I don't have libpython2.6.sohttp://stackoverflow.com/questions/1472828/how-can-i-link-against-libpython-a-such-that-later-the-runtime-linker-can-find-al
Ross Rogers