Error with c++ import in python

Hello,

I am trying to import c++ code in python following this tutorial : https://pytorch.org/tutorials/advanced/cpp_extension.html

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 :
test.py

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

test = load(
    name='test',
    sources=[os.path.join(module_path, "test_cpp.cpp")],
    extra_cflags=['-O2'],
    verbose=False)

and test_cpp.cpp

#include <iostream>

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

“python test.py” 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: https://pytorch.org/tutorials/advanced/cpp_extension.html#binding-to-python

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