python怎么导入math库_为什么在c中嵌入python时不能导入'math'库?

1586010002-jmsa.png

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

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?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值