How do you extend python with C++?

前端 未结 3 1234
生来不讨喜
生来不讨喜 2021-02-02 13:31

I\'ve successfully extended python with C, thanks to this handy skeleton module. But I can\'t find one for C++, and I have circular dependency trouble when trying to fix the err

3条回答
  •  借酒劲吻你
    2021-02-02 13:51

    use extern C to wrap all the function names that get called from python. Because C++ compilers use something called 'name mangling' (necessary for dealing with overloading), python can't read c++ libraries. But extern C will solve your problems. Do it like this:

    // most of your code can go whereever
    void cpp_function() {}
    extern "C" {
       // all functions that python calls directly must go in here
       void python_function() {}
    }
    

    Make extra sure you put every function python needs inside the extern block. You can still use c++ features inside the functions, it's just that the names will be exported without 'name mangling'.

提交回复
热议问题