我正在尝试使用Python的setuptools来构建这个示例的变体。在这个例子中,只有一个文件,main.cpp。但是,在我的版本中,我添加了另一个类。因此,总共有三个文件:
main.cpp
#include <pybind11/pybind11.h>
#include "myClass.h"
namespace py = pybind11;
PYBIND11_MODULE(python_example, m) {
m.doc() = R"pbdoc(
Pybind11 example plugin
)pbdoc";
py::class_<myClass>(m, "myClass")
.def(py::init<>())
.def("addOne", &myClass::addOne)
.def("getNumber", &myClass::getNumber)
;
}myClass.h
#include <pybind11/pybind11.h>
class myClass
{
public:
int number;
myClass();
void addOne();
int getNumber();
};myClass.cpp
#include <pybind11/pybind11.h>
#include "myClass.h"
myClass::myClass() {
number = 1;
}
void myClass::addOne() {
number = number + 1;
}
int myClass::getNumber() {
return number;
}如果我在示例中使用原始setup.py文件,它将无法工作,因为我需要将myClass.cpp与main.cpp链接起来。我怎样才能用setuptools做到这一点呢?基本上,我在寻找与setuptools等价的CMake的target_link_libraries。
我之所以这么问,是因为我在CMake方面的经验很少。使用setuptools对我来说会更容易。
发布于 2018-10-02 06:59:53
我相信你看到的是setuptools.Extension。我强烈建议您查看这个很好的示例:示例。它应该能引导你做你需要做的事情。
以下是我为您的代码提取的内容。请注意,它基本上是从示例复制粘贴。
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
import sys, re
import setuptools
import pybind11
# (c) Sylvain Corlay, https://github.com/pybind/python_example
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.distutils.errors.CompileError:
return False
return True
# (c) Sylvain Corlay, https://github.com/pybind/python_example
def cpp_flag(compiler):
if has_flag(compiler,'-std=c++14'): return '-std=c++14'
elif has_flag(compiler,'-std=c++11'): return '-std=c++11'
raise RuntimeError('Unsupported compiler: at least C++11 support is needed')
# (c) Sylvain Corlay, https://github.com/pybind/python_example
class BuildExt(build_ext):
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))
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)
ext_modules = [
Extension(
'python_example',
['main.cpp', 'myClass.cpp'],
include_dirs=[
pybind11.get_include(False),
pybind11.get_include(True ),
],
language='c++'
),
]
setup(
name = 'python_example',
ext_modules = ext_modules,
install_requires = ['pybind11>=2.2.0'],
cmdclass = {'build_ext': BuildExt},
zip_safe = False,
)请注意,代码的很大一部分并不处理特定的问题,而是让C++11/14以健壮的方式工作。我尽量把它保留在最初的例子中,也是为了在这里获得一个完整的工作代码。
https://stackoverflow.com/questions/52600067
复制相似问题