我正在尝试从包含main()使用的函数的C ++代码中调用python函数Pybind11。但是我发现很少有参考资料可用。现有的大多数文档都谈到了相反的方向,即从Python调用C ++。
有没有完整的示例说明如何执行此操作?我找到的唯一参考是:https : //github.com/pybind/pybind11/issues/30
但是它的信息很少。
Rom*_*tin 10
Jasons 的回答非常正确,但我想添加一个稍微复杂(和干净)的示例,该示例使用numpy输入调用 python 方法。我想展示两点:
py::object为 a py::functionusingpy::reinterpret_borrow<py::function>std::vector自动转换为一个numpy.array请注意,用户有责任确保它PyModule.attr实际上是一个 python 函数。另请注意,类型转换适用于多种c++类型(有关详细信息,请参见此处)。
在这个例子中,我想使用从 c++ 接口提供scipy.optimize.minimize的起始点的方法x0。
#include <iostream>
#include <vector>
#include <pybind11/pybind11.h>
#include <pybind11/embed.h> // python interpreter
#include <pybind11/stl.h> // type conversion
namespace py = pybind11;
int main() {
std::cout << "Starting pybind" << std::endl;
py::scoped_interpreter guard{}; // start interpreter, dies when out of scope
py::function min_rosen =
py::reinterpret_borrow<py::function>( // cast from 'object' to 'function - use `borrow` (copy) or `steal` (move)
py::module::import("py_src.exec_numpy").attr("min_rosen") // import method "min_rosen" from python "module"
);
py::object result = min_rosen(std::vector<double>{1,2,3,4,5}); // automatic conversion from `std::vector` to `numpy.array`, imported in `pybind11/stl.h`
bool success = result.attr("success").cast<bool>();
int num_iters = result.attr("nit").cast<int>();
double obj_value = result.attr("fun").cast<double>();
}
Run Code Online (Sandbox Code Playgroud)
使用 python 脚本 py_src/exec_numpy.py
import numpy as np
from scipy.optimize import minimize, rosen, rosen_der
def min_rosen(x0):
res = minimize(rosen, x0)
return res
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助某人!
这个问题的答案实际上包括两部分:一个关于从C ++调用Python函数,另一个关于嵌入解释器。
在pybind11中调用一个函数仅是将该函数放入一个pybind11::object变量中,您可以在该变量上调operator()用以尝试调用该对象。(它不一定是一个函数,而只是可以调用的东西:例如,它也可以是带有__call__方法的对象)。例如,math.sqrt(2)要使用C ++代码进行调用,您可以使用:
auto math = py::module::import("math");
auto resultobj = math.attr("sqrt")(2);
double result = resultobj.cast<double>();
Run Code Online (Sandbox Code Playgroud)
或者您可以将所有内容压缩为:
double result = py::module::import("math").attr("sqrt")(2).cast<double>();
Run Code Online (Sandbox Code Playgroud)
问题的第二部分涉及如何从C ++可执行文件执行此操作。构建可执行文件时(即,当C ++代码包含时main()),必须先将Python解释器嵌入二进制文件中,然后才能对Python进行任何操作(例如调用Python函数)。
嵌入式支持是当前pybind11 master分支(它将成为2.2版本)中添加的一项新功能。这是一个基本示例,该示例启动嵌入式Python解释器并调用Python函数(math.sqrt):
#include <pybind11/embed.h>
#include <iostream>
namespace py = pybind11;
int main() {
py::scoped_interpreter python;
auto math = py::module::import("math");
double root_two = math.attr("sqrt")(2.0).cast<double>();
std::cout << "The square root of 2 is: " << root_two << "\n";
}
Run Code Online (Sandbox Code Playgroud)
输出:
The square root of 2 is: 1.41421
Run Code Online (Sandbox Code Playgroud)
有关调用函数和嵌入的更多示例和文档,请访问http://pybind11.readthedocs.io/en/master/advanced/pycpp/object.html和http://pybind11.readthedocs.io/en/master/advanced/ embedding.html。
主程序
#include <pybind11/embed.h>
#include <iostream>
namespace py = pybind11;
using namespace py::literals;
int main() {
py::scoped_interpreter guard{};
// append source dir to sys.path, and python interpreter would find your custom python file
py::module_ sys = py::module_::import("sys");
py::list path = sys.attr("path");
path.attr("append")("..");
// import custom python class and call it
py::module_ tokenize = py::module_::import("calc");
py::type customTokenizerClass = tokenize.attr("CustomTokenizer");
py::object customTokenizer = customTokenizerClass("/Users/Caleb/Desktop/codes/ptms/bert-base");
py::object res = customTokenizer.attr("custom_tokenize")("good luck");
// show the result
py::list input_ids = res.attr("input_ids");
py::list token_type_ids = res.attr("token_type_ids");
py::list attention_mask = res.attr("attention_mask");
py::list offsets = res.attr("offset_mapping");
std::string message = "input ids is {},\noffsets is {}"_s.format(input_ids, offsets);
std::cout << message << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
计算程序
from transformers import BertTokenizerFast
class CustomTokenizer(object):
def __init__(self, vocab_dir):
self._tokenizer = BertTokenizerFast.from_pretrained(vocab_dir)
def custom_tokenize(self, text):
return self._tokenizer(text, return_offsets_mapping=True)
def build_tokenizer(vocab_dir: str) -> BertTokenizerFast:
tokenizer = BertTokenizerFast.from_pretrained(vocab_dir)
return tokenizer
def tokenize_text(tokenizer: BertTokenizerFast, text: str) -> dict:
res = tokenizer(text, return_offsets_mapping=True)
return dict(res)
Run Code Online (Sandbox Code Playgroud)
CMakeLists.txt
cmake_minimum_required(VERSION 3.4)
project(example)
set(CMAKE_CXX_STANDARD 11)
# set pybind11 dir
set(pybind11_DIR /Users/Caleb/Softwares/pybind11)
find_package(pybind11 REQUIRED)
# set custom python interpreter(under macos)
link_libraries(/Users/Caleb/miniforge3/envs/py38/lib/libpython3.8.dylib)
add_executable(example main.cpp)
target_link_libraries(example PRIVATE pybind11::embed)
Run Code Online (Sandbox Code Playgroud)