@Pyhon3x

Как использовать метод C++ в коде на Python?

Допустим есть код на Python где вызывается метод(допустим t.test()). Как сделать так чтобы метод test() был написан на C++

Типо модуль для Python на C++
Спасибо
  • Вопрос задан
  • 304 просмотра
Решения вопроса 1
sanya84
@sanya84
Фанатик Python 3
Сам напросился БАТАН)
С начала создаём заголовочный файл C++ (Да простят меня C++-шники:-))
Person.hpp
#ifndef PERSON_H
#define PERSON_H

#include <string>

using namespace std;

namespace person{
    class CppPerson{
        public:
            string name;
            int age;
            CppPerson();
            CppPerson(const string &name, const int &age);
            ~CppPerson();
            void setName(const string &name);
            string getName();
            int getAge();
    };
}
#endif

Далее реализация
Person.cpp
#include <string>
#include "Person.hpp"


namespace person{
    CppPerson::CppPerson(){}

    CppPerson::CppPerson(const string &name, const int &age){
        this->name = name;
        this->age = age;
    }
    CppPerson::~CppPerson(){}

    void CppPerson::setName(const string &name){
        this->name = name;
    }

    string CppPerson::getName(){
        return name;
    }

    int  CppPerson::getAge(){
        return age;
    }
}

Далее в дело вступает как раз таки Cython
person_module.pyx
from libcpp.string cimport string

cdef extern from "Person.hpp" namespace "person":
    cdef cppclass CppPerson:
        CppPerson(string name, int age) except +
        void setName(string name)
        string getName()
        int getAge()


cdef class Person:
    cdef CppPerson *cpp_person

    def __cinit__(self, name, age):
        self.cpp_person = new CppPerson(name.encode(), age)
        if self.cpp_person == NULL:
            raise MemoryError('Not enough memory.')

    def __dealloc__(self):
        del self.cpp_person
    def setName(self, name):
        self.cpp_person.setName(name.encode())
    def getName(self):
        return self.cpp_person.getName().decode()
    def getAge(self):
        return self.cpp_person.getAge()

Далее
setup.py
from distutils.core import setup, Extension
from Cython.Build import cythonize

setup(ext_modules = cythonize(Extension(
           "person_module",                                                 # the extesion name
           sources=["person_module.pyx", "Person.cpp"],     # the Cython source and
                                                                                       # additional C++ source files
           language="c++",                                                   # generate and compile C++ code
      )))

Теперь нужно всё это чудо скормить Cython-у
В той же папке где находятся все эти файлы запускаем cmd (Или с начала запускаем cmd а потом
переходим в эту директорию)

В cmd прописываем
python setup.py build_ext --inplace
Ну и тест
test.py
from person_module import Person

def main():
    alexandr = Person("Александр", 35)
    print(alexandr.getName())
    print(alexandr.getAge())

if __name__ == '__main__':
    main()

Документация о Cython
Ответ написан
Пригласить эксперта
Ответы на вопрос 2
NeiroNx
@NeiroNx
Программист
Ответ написан
Комментировать
@ardazishvili
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы