为什么 sip 在使用字符 * 时抱怨意外的类型"str"?



我正在尝试使用sip创建从c++到python 3.8的python绑定。我在这里找到了一个简单的例子并对其进行了更新,使其能够与我使用pip安装的sip 5.4版本一起工作。详细信息可以在这里找到

我把单词的名字改成了basicword,因为我用字符串重写并测试了单词示例。要做到这一点,我必须编写一堆特定于sip的代码,以使字符串库的导入工作正常,我认为必须有一种更简单的方法。

我的假设是,使用char*(就像在最初的教程中一样(会"更容易"啜饮,我缺少什么?

我的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 = ["."]

我的基本单词.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

我的basicford.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]='';
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'

谢谢你的回答!

再见Johnny

简而言之,Python2默认使用str类型,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";或";无";。编码";无";意味着相应的参数是指未编码的字符或字符串。

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;
};

现在一切正常。

最新更新