I have a python project that I want to call from a c++ application. I would like to bundle all python sources together in a single shared library and link the c++ application to that library. Right now my cython setup.py creates one *.so
per python source, which is very inconvenient.
Here is the setup.py
file:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
sourcefiles = ['project_interface.pyx', 'impl_file1.pyx']
setup(
ext_modules = cythonize(sourcefiles)
)
project_interface.pyx :
# distutils: language = c++
import impl_file1
cdef public void HelloWorld():
print "Calling Hello World"
impl_file1.helloworld_func()
impl_file1.pyx :
def helloworld_func():
print 'Hello World'
I tried to modify setup.py to bundle all python code in a single library like this:
setup(
ext_modules = cythonize([Extension("my_project", sourcefiles, language='c++')])
)
Unfortunately, when executing void HelloWorld()
, the application cannot file impl_file1 anymore. I get :
Calling Hello World
NameError: name 'impl_file1' is not defined
Exception NameError: "name 'impl_file1' is not defined" in 'project_interface.HelloWorld' ignored
The c++ program driving this is:
#include <Python.h>
#include "project_interface.h"
int main(int argc, const char** argv){
Py_Initialize();
initproject_interface();
HelloWorld();
Py_Finalize();
return 0;
}
This application works correctly when compiling with multiple *.so
files.
Compilation is very straightforward in either cases:
python setup.py build_ext --inplace
mv my_project.so libmy_project.so
g++ main.cpp -o main `python2-config --cflags --ldflags` -L. -lmy_project
Is there any way to get the single shared library solution to work?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…