简体   繁体   中英

Cython 'module' object has no attribute

In my pyx file, I defined two C functions and wrapped by python functions. It's complied successfully and output a file with name Rand_Motion.cpython-34m.so . However, I can't access either function defined in the pyx file in my main file with import Rand_Motion. This is my Rand_Motion.pyx :

cdef extern from "math.h":
    float cosf(float theta)  
    float sinf(float theta)          
    float acosf(float theta)    
    float sqrt(float x)

cdef object randmotion_c(int Dimension,float Diffcoe, float pos_x,float pos_y, float pos_z,float drift_l,float drift_a,float drift_b,float a,float b):
    cdef float length=sqrt(2*Dimension*Diffcoe)
    cdef float pi= 3.1415926535
    cdef float e=  2.7182818284
    cdef float a_d=a*2*pi
    cdef float b_d=acosf(1-b*2)

    pos_x+=length*sinf(b_d) *cosf(a_d)
    pos_y+=length*sinf(b_d) *sinf(a_d)
    pos_z+=length*cosf(b_d)    

    if  drift_l>0:
        drift_a=(drift_a/180)*pi
        drift_b=(drift_b/180)*pi
        pos_x+=drift_l*sinf(drift_a) *cosf(drift_b)
        pos_y+=drift_l*sinf(drift_a) *sinf(drift_b) 
        pos_z+=drift_l*cosf(drift_a)        
    return pos_x,pos_y,pos_z

def randmotion(Dimension,Diffcoe, pos_x,pos_y,pos_z,drift_l,drift_a,drift_b,a,b):

    return randmotion_c(Dimension,Diffcoe, pos_x,pos_y,pos_z,drift_l,drift_a,drift_b,a,b)

cdef dis_cal_c(float x,float y,float z):
    return sqrt(x*x+y*y+z*z)

def dis_cal(x,y,z):
    return dis_cal_c(x,y,z) 

I copy/pasted your code in a aaa.pyx file, then I runned :

mgc@mgc-X:~/code/test$ cythonize aaa.pyx
mgc@mgc-X:~/code/test$ gcc -shared -fPIC -fwrapv -O2 -Wall -I/usr/include/python3.4 -o aaa.so aaa.c
mgc@mgc-X:~/code/test$ python3
Python 3.4.3 (default, Mar 26 2015, 22:03:40) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from aaa import randmotion, dis_cal
>>> dis_cal(1,2,3)
3.7416573867739413

and it seems working perfectly ( note that I run python in the same directory as the shared object ). Maybe you want to install your shared library ? Take a look at cython documentation about compilation or at python documentation about installing modules .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM