PyBind11: конструктор, который использует указатель на строку - PullRequest
0 голосов
/ 09 мая 2018

Мне удалось связать этот конструктор

.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 то, что напоминает константную строку *

1 Ответ

0 голосов
/ 12 мая 2018

main.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
...