Ask Your Question
0

Create a Python module with pybind11 and use it in another package

asked 2020-09-23 08:53:11 -0500

hdino gravatar image

I'm trying to build a Python module with pybind11 in package pkg1 and use it from package pkg2. Is there any example of how to do this?

I tried the following:

  1. ros2 pkg create pkg1
  2. Add the following to pkg1's CMakeLists.txt:

_

find_package(pybind11 REQUIRED)
pybind11_add_module(pkg1 src/example.cpp)

install(
  TARGETS pkg1
  LIBRARY DESTINATION lib
  ARCHIVE DESTINATION lib
  RUNTIME DESTINATION bin
  INCLUDES DESTINATION include
)

Building this package creates pkg1.cpython-38-x86_64-linux-gnu.so in install/pkg1/lib.

Then I created pkg2:

ros2 pkg create --build-type ament_python --node-name pkg2_demo pkg2

To its package.xml I added <depend>pkg1</depend>. However, I know that a few steps are missing until I can call import pkg1 from a Python script in pkg2. Can anyone help?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2020-09-24 04:07:13 -0500

hdino gravatar image

I found a way to do it. pkg1's CMakeLists.txt should look like this:

cmake_minimum_required(VERSION 3.5)
project(pkg1)
find_package(ament_cmake REQUIRED)
find_package(pybind11 REQUIRED)

ament_python_install_package(${PROJECT_NAME})

pybind11_add_module(mymodule src/example.cpp)
install(TARGETS mymodule
  DESTINATION "${PYTHON_INSTALL_DIR}/${PROJECT_NAME}"
)

ament_package()

example.cpp:

#include <pybind11/pybind11.h>
int add(int i, int j) { return i + j; }
PYBIND11_MODULE(mymodule, m)
{
    m.def("add", &add, "A function which adds two numbers");
}

Finally, one needs to create my_workspace/src/pkg1/pkg1/__init__.py with the following content:

from pkg1.mymodule import *

After sourcing my_workspace/install/setup.sh one can start Python and do:

>>> import pkg1
>>> pkg1.add(5,3)
8
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

2 followers

Stats

Asked: 2020-09-23 08:53:11 -0500

Seen: 29 times

Last updated: Sep 24