c++ 使用swig Python Package 器:类型“std::unordered_set const &amp;”的参数2< std::string >

5vf7fwbs  于 2023-05-02  发布在  Python
关注(0)|答案(2)|浏览(189)

我正在使用SWIG从C生成的Python包coqui_stt_ctcdecoder(的父项目)更新一个旧项目。某些方法中的某些参数类型已更改。我被Scorer::fill_dictionary方法卡住了,它将const std::unordered_set<std::string>&作为C中的参数。在旧的Python代码中,传递了一个bytes的列表,但这不再起作用,还有一个集合。我不知道该放什么类型的。错误是

Traceback (most recent call last):
  File "/mnt/d/shared/speech/dsalign/STT-align/align/align.py", line 693, in <module>
    main()
  File "/mnt/d/shared/speech/dsalign/STT-align/align/align.py", line 451, in main
    create_bundle(alphabet_path, scorer_path + '.' + 'lm.binary', scorer_path + '.' + 'vocab-500000.txt', scorer_path, False, 0.931289039105002, 1.1834137581510284)
  File "/mnt/d/shared/speech/dsalign/STT-align/align/generate_package.py", line 75, in create_bundle
    scorer.fill_dictionary(words)
  File "/mnt/d/shared/speech/dsalign/STT-align/venv/lib/python3.10/site-packages/coqui_stt_ctcdecoder/swigwrapper.py", line 1269, in fill_dictionary
    return _swigwrapper.Scorer_fill_dictionary(self, vocabulary)
TypeError: in method 'Scorer_fill_dictionary', argument 2 of type 'std::unordered_set< std::string > const &'

编辑:我已经尝试了一个列表和一组strbytes,都有上面的例外。我用的是Python 3。8在Windows和WSL上。

jqjz2hbq

jqjz2hbq1#

SWIG包括对std::unordered_set的支持,但请注意,该接口奇怪地不接受Python set对象。但是,tuplelist可以工作。
测试示例:

test.i

%module test

// Code injected into wrapper
%{
#include <iostream>
#include <string>
#include <unordered_set>

// Function using the parameter type from OP error message
void func(std::unordered_set<std::string> const &string_set) {
    for(auto& s : string_set)
        std::cout << s << std::endl;
}
%}

// SWIG support for templates
%include <std_unordered_set.i>
%include <std_string.i>
// Must instantiate the specific template used
%template(string_set) std::unordered_set<std::string>;

// Tell SWIG to wrap the function
void func(std::unordered_set<std::string> const &string_set);

演示:

>>> import test
>>> test.func(['abc','def','abc','ghi'])  # list works
abc
def
ghi
>>> s = test.string_set(['aaa','bbb','ccc','aaa','bbb'])
>>> test.func(s)
aaa
bbb
ccc
>>> s = test.string_set(('aaa','bbb','ccc','aaa','bbb')) # tuple works
>>> list(s)
['aaa', 'bbb', 'ccc']
>>> test.func({'abc','def'})  # set doesn't work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\test.py", line 194, in func
    return _test.func(string_set)
TypeError: in method 'func', argument 1 of type 'std::unordered_set< std::string,std::hash< std::string >,std::equal_to< std::string >,std::allocator< std::string > > const &'
q35jwt9p

q35jwt9p2#

一个修复程序已经投入工作的方块swig-4。2.0释放
前面的实现使用Python序列协议将Python类型转换为STL容器。新的实现使用Python迭代器协议,因此也可以从Python集合转换。

相关问题