3

我有一个工作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文件中实现的功能。

4

0 回答 0