2

I am using PyBind11 to make a Python project.

My directory structure looks a like this:

./
  my_pkg/
    __init__.py
    func1.py
    func2.py

My C++ code looks like this:

int myfunc(){
  return 1;
}

PYBIND11_PLUGIN(cppmodule) {
  py::module m("cppmodule", "My cpp module");

  m.def("myfunc",&myfunc,"This does stuff");

  return m.ptr();
}

And my setup.py looks like this:

from setuptools import setup, Extension
import glob

ext_modules = [
  Extension(
    "cppmodule",
    glob.glob('src/*.cpp'),
    include_dirs       = ['lib/include', 'lib/pybind11/'],
    language           = 'c++',
    extra_compile_args = ['-std=c++17'],
    define_macros      = [('DOCTEST_CONFIG_DISABLE',None)]
  )
]

setup(name = 'bob',
  version      = '0.1',
  description  = 'A package about shrimp',
  url          = 'http://github.com/shrimp',
  author       = 'Bob',
  author_email = '',
  license      = 'MIT',
  ext_modules  = ext_modules
)

Now, if I runn

python setup.py install

everything compiles.

But here's the odd part, later, I can run import cppmodule but not import bob. Or, with other fiddling, sometimes I can run both.

What I have not figured out how to do, but what I would like to do, is to have the C++ code incorporated into the bob module the same way func1 and func2 will be, so that I can type bob.myfunc() in Python.

How can I do this?

2
  • Have you tried exposing those functions in __init__.py? Commented Aug 12, 2017 at 2:36
  • @krassowski: If I tell setup not to build the C++ stuff, then the functions expose automatically. I think two packages are getting declared and PyBind is taking precedence. But I will check on your suggestion shortly. Commented Aug 12, 2017 at 3:03

1 Answer 1

2

The answer was to modify the code in setup.py to look like:

from setuptools import setup, Extension, find_packages

setup(name = 'bob',
  version      = '0.1',
  description  = 'A package about shrimp',
  url          = 'http://github.com/shrimp',
  author       = 'Bob',
  author_email = '',
  license      = 'MIT',
  packages     = find_packages(),
  ext_modules  = ext_modules
)
Sign up to request clarification or add additional context in comments.

2 Comments

currently having the same problem ... using this answer, are you able to call bob.myfunc() now or do you have two packages installed now?
@BenjaminMaier: I see that I've answered the question less clearly than I could have. What I do now when I want a package named bob is to compile the pybind11 code into a package named _bob and then in __init__.py I import a bunch of stuff from _bob to make it available in bob.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.