python封裝C++接口

開源項目pybind11
項目主要功能是將C++代碼封裝爲Python接口,與boost.python類似,但比它小很多
1、下載pybind11
https://github.com/pybind/pybind11.git
2、安裝pybind11
pip install pybind11-master
3、編寫接口
example.cpp

int add(int i,int j){
	return i +j;
}
PYBIND11_MODULE(my_example,m){
	m.def("add",&add,"i"_a,"j"_b);
}

4、編寫安裝文件
setup.py

from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
import sys
import setuptools

__version__= '0.0.1'
class get_pybind_include(object):
	def __init__(self,user=False):
		sef.user = user
	def __str__(self):
	  import pybind11
	  return pybind11.get_include(self.user)
	  
ext_modules = [
	Extension(
		'my_example',
		['example.cpp'],
		include_dirs=[
			get_pybind_include(),
			get_pybind_include(user=True)
		],
		language='c++'
	),
]
def has_flag(compiler, flagname):
	import tempfile
	with tempfile.NamedTemporaryFile('w',suffix='.cpp') as f:
		f.write('int main (int argc, char **argv){return 0;}')
		try:
			compiler.compile([f.name],extra_postargs=[flagname])
		except setuptools.setuptools.distutils.errors.CompileError:
            return False
    return True


def cpp_flag(compiler):
    """Return the -std=c++[11/14] compiler flag.

    The c++14 is prefered over c++11 (when it is available).
    """
    if has_flag(compiler, '-std=c++14'):
        return '-std=c++14'
    elif has_flag(compiler, '-std=c++11'):
        return '-std=c++11'
    else:
        raise RuntimeError('Unsupported compiler -- at least C++11 support '
                           'is needed!')


class BuildExt(build_ext):
    """A custom build extension for adding compiler-specific options."""
    c_opts = {
        'msvc': ['/EHsc'],
        'unix': [],
    }

    if sys.platform == 'darwin':
        c_opts['unix'] += ['-stdlib=libc++', '-mmacosx-version-min=10.7']

    def build_extensions(self):
        ct = self.compiler.compiler_type
        opts = self.c_opts.get(ct, [])
        if ct == 'unix':
            opts.append('-DVERSION_INFO="%s"' % self.distribution.get_version())
            opts.append(cpp_flag(self.compiler))
            if has_flag(self.compiler, '-fvisibility=hidden'):
                opts.append('-fvisibility=hidden')
        elif ct == 'msvc':
            opts.append('/DVERSION_INFO=\\"%s\\"' % self.distribution.get_version())
        for ext in self.extensions:
            ext.extra_compile_args = opts
        build_ext.build_extensions(self)

setup(
    name='my_example',
    version=__version__,
    author='Sylvain Corlay',
    author_email='[email protected]',
    url='https://github.com/pybind/python_example',
    description='A test project using pybind11',
    long_description='',
    ext_modules=ext_modules,
    install_requires=['pybind11>=2.2'],
    cmdclass={'build_ext': BuildExt},
    zip_safe=False,
)

5、安裝
pip install myexample
6、測試代碼

> import my_example
> my_example.add(3,4)
7
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章