cpp
で問題なくビルドできる作業中のプロジェクトがありますcmake
。今度は、同じための Python ラッパーを作成する必要があります。そこで、とcython
の間のギャップを埋めることにしました。C++
Python
CMakeLists.txt
ロジックをpyx
ファイルに記述する代わりに、ライブラリをcmake
それ自体でコンパイルし、後で Cython ラッパーをラップしてみました。setup.py
ファイルは次のとおりです。
import os
import sys
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
try:
build_dir = os.path.join(os.getcwd(), "build")
print("building bobcore.a")
if not os.path.exists(build_dir):
os.makedirs(build_dir)
if not os.path.exists(build_dir):
raise Exception("Not able to create `build` directory")
os.chdir(build_dir)
assert os.system("cmake ..") == 0
assert os.system("make -j4") == 0
os.chdir(os.path.abspath(os.path.join(os.getcwd(), os.pardir)))
except:
if not os.path.exists("build/bobcli"):
print("Error building external library, please create libsample.a manually.")
sys.exit(1)
_ext_modules = cythonize([
Extension("call_core",
sources=["call_core.pyx"],
language="c++",
extra_compile_args=["-std=c++11", "-lpthread", "-lz", "-ldl"],
extra_link_args=["-std=c++11"],
include_dirs=[os.path.join(os.getcwd(), "src")], # path to .h file(s)
library_dirs=[os.path.join(os.getcwd(), "build")], # path to .a or .so file(s)
libraries=["bobcli"] # name of pre-built .so file.
)
])
setup(
name='Demos',
ext_modules=_ext_modules,
)
call_core.pyx
ファイルは次のとおりです。
cdef extern from "src/api/Api.h" namespace "cli":
cdef cppclass Api:
int getVal()
cdef Api *api = new Api()
def getHelp():
return api.getVal()
del api
getVal()
ヘッダーファイル自体にメソッドを実装すると、このファイルは正常に機能します。しかし、実装を.cpp
ファイルに移動するとすぐに、Cython コンパイラーは次のエラーを表示します。
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: /usr/local/lib/python2.7/dist-packages/call_core.so: undefined symbol: _ZN3cli9Api6getValEv
注: 上記のスニペットは、ファイルに実装されている関数に対して完全に機能し.h
ます。