python - PyBind11:使用指向字符串的指针的构造函数

标签 python c++ string constructor pybind11

我成功绑定(bind)了这个构造函数

.def(py::init<const int, const int, const string *>())

我的问题是当我必须使用字符串数组时,如果我喜欢这样
alph2=['x','y']
z=Dfa(3,2,alph2)

它没有说:
TypeError: __init__(): incompatible constructor arguments. The
following argument types are supported:
gi_gipy.Dfa(arg0: int, arg1: int, arg2: unicode)

所以我不知道如何从 python 传递类似于 const string* 的东西

最佳答案

主.cpp:

#include <iostream>
#include <list>
#include "pybind11/pybind11.h"

void Dfa(const int n_state, const std::size_t size, const char* alpha) {
    std::cout << "n_state: " << n_state << "\n";
    std::cout << "size: " << size << "\n";
    std::cout << "alpha: " << alpha << "\n";
}

void dfa_wrapper(int n_state, std::string alpha) {
    // Copy the python unicode string 
    // and make a c++ std::string.
    // Modifying this copy won't change
    // the original python string.
    Dfa(n_state, alpha.size(), alpha.data());
}

PYBIND11_MODULE(_cpp, m) {
    m.def("dfa", &dfa_wrapper, "Wrapper of your Dfa::dfa");
}

CMakeLists.txt:
cmake_minimum_required(VERSION 3.9)
project(test_pybind11)

set(CMAKE_CXX_STANDARD 11)

# Find packages.
set(PYTHON_VERSION 3)
find_package( PythonInterp ${PYTHON_VERSION} REQUIRED )
find_package( PythonLibs ${PYTHON_VERSION} REQUIRED )

# Download pybind11
set(pybind11_url https://github.com/pybind/pybind11/archive/stable.zip)

set(downloaded_file ${CMAKE_BINARY_DIR}/pybind11-stable.zip)
file(DOWNLOAD ${pybind11_url} ${downloaded_file})
execute_process(COMMAND ${CMAKE_COMMAND} -E tar xzf ${downloaded_file}
        SHOW_PROGRESS)
file(REMOVE ${downloaded_file})

set(pybind11_dir ${CMAKE_BINARY_DIR}/pybind11-stable)
add_subdirectory(${pybind11_dir})
include_directories(${pybind11_dir}/include)

# Make python module
pybind11_add_module(_cpp main.cpp)

Python 3 测试:
>>> import _cpp
>>> _cpp.dfa(1, "xyz")
n_state: 1
size: 3
alpha: xyz

关于python - PyBind11:使用指向字符串的指针的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50256698/

相关文章:

php - 用于匹配(并删除)包含文件中的多行 PHP 代码的正则表达式模式

c++ - 来自初始化列表的隐式类型转换在一种情况下编译但在另一种情况下不编译

c++ - 每次调用 std::cout 时打印时间

c++ - 为头文件创建源文件

java - 只需在java中复制一个子字符串

python - 用于删除具有重复整数的数字的函数会跳过一项,我不知道为什么

c# - Python XML Parse(使用模式生成数据集)

python - 属性值中不允许使用未转义的 '<'

python - BeautifulSoup 插入 HTML 数据属性

java - 用不可见字符(制表符、回车符、组分隔符等)分隔字符串?