简体   繁体   中英

segmentation fault - Python -> C

My code is:

#!/usr/bin/python
import os
os.system('ls')

I converted it to C code using cython:

~ $ cython ostest.py
~ $ ls ostest*
ostest.c  ostest.py

Then compiled C file using gcc:

~ $ gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing \-I/usr/include/python2.7 -o ostest.so ostest.c
~ $ ls ostest*
ostest.c  ostest.py  ostest.so

And when I tried to execute the file, its giving error:

~ $ ./ostest.so
Segmentation fault

I checked the file permissions:

~ $ ls -l ostest.so
-rwxr-xr-x

The python code I mentioned above is just a sample. I tried doing the same with other python programs I have written. For all of them, I'm getting the same error.
How to solve this?

Trying to execute a shared library (which is what you're building by using the -shared flag with GCC) is going to result in a segmentation fault. That's because you're not meant to run a shared library. It appears you've misread the instructions for Cython Compilation -- which clearly states that the command you've used is for compiling extension modules (C code which you can import from Python). Cython is not for making standalone Python programs, it's for compiling Python extension modules to C. You'll still need to run a Python interpreter to use them.

If you want to compile your Python code to be a standalone binary (whatever that means -- all binaries except statically linked binaries have some dependancy on system libraries), you might want to take a look at this SO question: How to make a Python script standalone executable to run without ANY dependency?

You can use Nuitka , which is a Python compiler than can produce standalone executables that I've heard good things about.

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