我很清楚用户已经解决了他的问题,但这里有一个解决方案。可能会引入一些输入验证,以避免输入字典的非字符串值。
头文件
// File: test.h
#pragma once
#include <iostream>
#include <string>
#include <unordered_map>
void method(std::unordered_map<std::string, std::string>* inout) {
for(const auto& n : (*inout)) {
std::cout << "Key:[" << n.first << "] Value:[" << n.second << "]\n";
}
(*inout)["BLACK"] = "#000000";
};
接口文件
// File : dictmap.i
%module dictmap
%{
#include "test.h"
%}
%include "typemaps.i"
%typemap(in) std::unordered_map<std::string, std::string>* (std::unordered_map<std::string, std::string> temp) {
PyObject *key, *value;
Py_ssize_t pos = 0;
$1 = &temp;
temp = std::unordered_map<std::string, std::string>();
while (PyDict_Next($input, &pos, &key, &value)) {
(*$1)[PyString_AsString(key)] = std::string(PyString_AsString(value));
}
}
%typemap(argout) std::unordered_map<std::string, std::string>* {
$result = PyDict_New();
for(const auto& n : *$1) {
PyDict_SetItemString($result, n.first.c_str(),
PyString_FromString(n.second.c_str()));
}
}
%include "test.h"
测试
import dictmap
out = dictmap.method({'WHITE' : '#FFFFFF'})
输出是更新的辞典
In[2]: out
Out[3] : {'BLACK': '#000000', 'WHITE': '#FFFFFF'}
非常感谢,m7thon!第二颗子弹是我失踪的作品。从提供的Swig示例中,我认为您的最后一个项目符号是传回数据的唯一可能方式(通过使用返回值)。 –
@wr m7thon与这个答案是现货。你必须注意的一件事就是让你自己记住,Python开发者(即你的绑定的用户)期望的行为是。理想情况下,你想采取最不容易混淆的路线。对我来说,通常在Python中,输入参数是不变的,因为与C++不同,你不能轻易推断(例如)通过const /不引用行为是什么。这几乎只留下了一个返回值作为选项,这通常是有道理的,因为返回值并没有用于指示设计良好的接口的成功/失败。 – Flexo