Почему sip жалуется на неожиданный тип str при использовании char *?

Я пытаюсь использовать 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'

Спасибо за ваш ответ!

Пока Джонни


person JohnnyWaker    schedule 21.10.2020    source источник
comment
Пожалуйста, отредактируйте свой вопрос, включив в него полную и полную информацию об ошибке. И если есть ссылка на файл и строку, добавьте комментарий в этот файл и в эту строку, чтобы показать, где вы получили ошибку.   -  person Some programmer dude    schedule 21.10.2020
comment
извините, забыл тестовый файл и сообщение об ошибке   -  person JohnnyWaker    schedule 21.10.2020


Ответы (1)


Короче говоря, Python2 использует по умолчанию str-type и байтовый тип python3, поэтому мне пришлось изменить кодировку по умолчанию для python3.

Я нашел соответствующую информацию здесь

Кодирование

This string annotation specifies that the corresponding argument (which should be either char, const char, char * or const char *)

относится к закодированному символу или закодированной строке с завершением '\ 0' с указанной кодировкой. Кодировка может быть ASCII, Latin-1, UTF-8 или None. Кодировка None означает, что соответствующий аргумент относится к незакодированному символу или строке.

The default encoding is specified by the %DefaultEncoding directive. If the directive is not specified then None is used.

Python v3 will use the bytes type to represent the argument if the encoding is "None" and the str type otherwise.

Python v2 will use the str type to represent the argument if the encoding is "None" and the unicode type otherwise.

С помощью следующего простого добавления в basicword.sip ...

// Define the SIP wrapper to the basicword library.

%Module(name=basicword, language="C++")

%DefaultEncoding "UTF-8" // Missing Encoding!

class Basicword {

%TypeHeaderCode
#include <basicword.h>
%End

public:
    Basicword(const char *w);

    char *reverse() const;
};

теперь все работает.

person JohnnyWaker    schedule 22.10.2020