How to build a Cython extension using CMake

12 views
Skip to first unread message

Corbin Foucart

unread,
Apr 21, 2022, 12:14:57 AM4/21/22
to cython-users
Hello everyone,

I'm new to Cython, and I have the following problem:
  • I have a very complicated C++ library with lots of dependencies which I would like to wrap with Cython
  • I build the library, including the shared object file I'd like to wrap, using CMake
  • I need all the CMake information in order to compile the Cython code, but don't know how to incorporate it
For example, if I declare a simple class, similar to the tutorial (but try to #include something from my complicated library):

binding.h:
#ifndef BINDING_H
#define BINDING_H

namespace TestClass
{

class Rectangle
{
  public:

    Rectangle();
    ~Rectangle();

    void talk();
    int x;
};

}
#endif

binding.cc

#include <iostream>
#include "binding.h"

// this file is discoverable when building the so with cmake
#include <my_complicated_library/include/header.h>

namespace TestClass
{

Rectangle::Rectangle()
  : x(16)
{}

Rectangle::~Rectangle() {}

void Rectangle::talk()
{
  std::cout << "test class printed, x:" << x << std::endl;
}
}


and the usual rect.pyx and rect.pyd wrapping the two C++ files, I can compile the shared object file in CMakeLists.txt

CMakeLists.txt:

// complicated build procedure
...

// binding library
ADD_LIBRARY(binding_lib SHARED binding.cc)
COMPLICATED_SETUP_MACRO(binding_lib)

Running cmake is able to build the shared object file fine, but running setup.py

from setuptools import setup
from Cython.Build import cythonize

setup(ext_modules=cythonize("rect.pyx"))

fails, as it has no idea how to resolve the #include <my_complicated_libary/head.h> statement; I get the expected "fatal error: my_complicated_library/header.h: no such file or directory'. If I remove this line, everything works fine, but I can't use the definitions in my C++ library. This particular header has many other dependencies managed by CMake, so I don't think it's a matter of adding an include directory.

It seems the best way would be doing the Cython compilation in CMake directly, but I don't know how to do that. I can't be the only one attempting to wrap a library built by CMake.

Any guidance would be greatly appreciated!

Corbin



Reply all
Reply to author
Forward
0 new messages