pybind11 字符串、字节和Unicode转换

2022-04-22  本文已影响0人  JeremyL
#include <pybind11/pybind11.h>
#include <vector>
#include <iostream>
#include <pybind11/stl.h>
using namespace std;
namespace py = pybind11;


int add(int i, int j) {
    return i + j;
}

int a= 1;
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
vector<int> vecMyHouse(10,3); 

PYBIND11_MODULE(Passing, m) {
    m.doc() = "pybind11 example plugin"; // optional module docstring

// Function
    m.def("add", &add, "A function that adds two numbers");

// Passing Python strings to C++
    m.def("utf8_test",
    [](const std::string &s) {
        std::cout << "utf-8 is icing on the cake.\n";
        std::cout << s;
    }
);
//utf8_test("🎂")
m.def("utf8_charptr",
    [](const char *s) {
        std::cout << "My favorite food is\n";
        std::cout << s;
    }
);
//utf8_charptr("🍕")
// Returning C++ strings to Python
m.def("std_string_return",
    []() {
        return std::string("This string needs to be UTF-8 encoded");
    }
);
//isinstance(example.std_string_return(), str)
// Explicit conversions
// This uses the Python C API to convert Latin-1 to Unicode
/*
m.def("str_output",
    []() {
        std::string s = "Send your r\xe9sum\xe9 to Alice in HR"; // Latin-1
        py::str py_s = PyUnicode_DecodeLatin1(s.data(), s.length());
        return py_s;
    }
);//str_output()

*/

// Return C++ strings without conversion
m.def("return_bytes",
    []() {
        std::string s("\xba\xd0\xba\xd0");  // Not valid UTF-8
        return py::bytes(s);  // Return the data without transcoding
    }
);// example.return_bytes()
m.def("asymmetry",
    [](std::string s) {  // Accepts str or bytes from Python
        return s;  // Looks harmless, but implicitly converts to str
    }
);
//isinstance(example.asymmetry(b"have some bytes"), str)
// Character literals
m.def("pass_char", [](char c) { return c; });
m.def("pass_wchar", [](wchar_t w) { return w; });
// example.pass_char("A")
// return value
m.def("aValue",
    []() {
        return a;
    }
);
m.attr("the_answer") = 42;
py::object world = py::cast("World");
m.attr("what") = world;

// return vector
m.def("vecMyHouse",
    []() {
        return vecMyHouse;
    }
);
py::object vecMyHouse2 = py::cast(vecMyHouse);
m.attr("vecMyHouse2") = vecMyHouse2; //Passing.vecMyHouse2
m.attr("vecMyHouse3") = vecMyHouse;

}

g++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup `python3 -m pybind11 --includes` Passing.cpp -o Passing`python3-config --extension-suffix`
>>> import Passing
>>> Passing.vecMyHouse2
[3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
>>> Passing.aValue()
1

# 原文

[Strings, bytes and Unicode conversions

上一篇下一篇

猜你喜欢

热点阅读