Я пытаюсь использовать sip для создания привязок python от c ++ к python 3.8. Я нашел здесь простой пример и обновил его, чтобы он работал с sip версии 5.4, которая Я установил с помощью пипса. Подробности можно найти здесь
Я изменил имена со слова на базовое слово, потому что я переписал и протестировал пример слова со строками. Для этого мне пришлось написать кучу кода, специфичного для sip, чтобы заставить работать импорт строковой библиотеки, и подумал, что должен быть более простой способ.
Я исходил из предположения, что использование char * (как в исходном руководстве) было бы «проще» для sip, что мне не хватает?
Мой файл sip basicword.sip:
// Define the SIP wrapper to the basicword library.
%Module(name=basicword, language="C++")
class Basicword {
%TypeHeaderCode
#include <basicword.h>
%End
public:
Basicword(const char *w);
char *reverse() const;
};
Мой файл pyproject.toml:
# Specify sip v5 as the build system for the package.
[build-system]
requires = ["sip >=5, <6"]
build-backend = "sipbuild.api"
# Specify the PEP 566 metadata for the project.
[tool.sip.metadata]
name = "basicword"
# Configure the building of the basicword bindings.
[tool.sip.bindings.basicword]
headers = ["basicword.h"]
include-dirs = ["."]
libraries = ["basicword"]
library-dirs = ["."]
Мой файл basicword.h:
#ifndef BASICWORD_H
#define BASICWORD_H
// Define the interface to the basicword library.
class Basicword {
private:
const char *the_word;
public:
Basicword(const char *w);
char *reverse() const;
};
#endif //BASICWORD_H
Мой файл basicword.cpp:
#include "basicword.h"
#include <cstring>
Basicword::Basicword(const char *w) {
the_word = w;
}
char* Basicword::reverse() const {
int len = strlen(the_word);
char *str = new char[len+1];
for(int i = len-1;i >= 0 ;i--) {
str[len-1-i] = the_word[i];
}
str[len+1]='\0';
return str;
}
Мой файл test.py:
from basicword import Basicword
w = Basicword("reverse me") // -> error thrown here
if __name__ == '__main__':
print(w.reverse())
Сообщение об ошибке:
Traceback (most recent call last):
File "<path to testfile>/test.py", line 3, in <module>
w = Basicword("reverse me")
TypeError: arguments did not match any overloaded call:
Basicword(str): argument 1 has unexpected type 'str'
Basicword(Basicword): argument 1 has unexpected type 'str'
Спасибо за ваш ответ!
Пока Джонни