Error with c++ import in python


I am trying to import c++ code in python following this tutorial :

However i’m running into an error that I don’t understand :

ImportError: dynamic module does not define module export function (PyInit_test)

It is very simple to reproduce the error:
I use two files :

import os
from torch.utils.cpp_extension import load
module_path = os.path.dirname(__file__)

test = load(
    sources=[os.path.join(module_path, "test_cpp.cpp")],

and test_cpp.cpp

#include <iostream>

int placeholder() {
    std::cout << "hello" << '\n';
    return 0;

“python” to reproduce the error.

Do you have any idea where this error could come from ?

You need to configure Python bindings using the pybind11 macros shown here:

Remember to also include the extension header — #include <torch/extension.h>

I would highly recommend reading the entire tutorial (perhaps even twice) to get an understanding of all the mechanisms in play here. Lots of moving parts, and definitely not trivial.

Good luck and have fun :slight_smile:

Thanks for your answer, it works :slight_smile:

Have a good day !

1 Like