簡體   English   中英

pybind11基本回調,不兼容的函數簽名錯誤

[英]pybind11 basic callback, incompatible function signature error

我一生無法獲得一個非常基本的Python回調函數在pybind11構建的擴展模塊中工作。 我正在嘗試遵循此處的示例,但我想我一定是誤會了一些東西。

C ++代碼如下:

#include <iostream>
#include <functional>
#include <pybind11/pybind11.h>

namespace py = pybind11;

void run_test(const std::function<int(int)>& f)
{
   // Call python function?
   int r = f(5);
   std::cout << "result: " << r << std::endl;
}

PYBIND11_PLUGIN(mymodule)
{
    py::module m("mymodule");
    m.def("run_test", &run_test);
    return m.ptr();
} 

使用此模塊的Python代碼是

import mymodule as mm

# Test function
def test(x):
  return 2*x

mm.run_test(test)

但是我得到這個錯誤:

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    mm.run_test(test)
TypeError: run_test(): incompatible function arguments. The following argument types are supported:
    1. (arg0: std::function<int (int)>) -> None

Invoked with: <function test at 0x2b506b282c80>

為什么它認為功能簽名不匹配? 我試圖匹配這些示例,但我想我必須誤解了一些...

好的,我誤解了為什么在該示例中使用了std :: function。 那是為了進行更復雜的兩次回調,在此過程中,將C ++函數傳遞給Python,然后又傳遞回C ++,以檢查它在整個過程中是否還存在。 對於剛剛調用Python函數一個需要使用py::object和把結果到C ++型(如所描述的在這里 ):

void run_test(const py::object& f)
{
   // Call python function?
   py::object pyr = f(5);
   int r = pyr.cast<int>();
   std::cout << "result: " << r << std::endl;
}

我相信您的問題是您忘記了#include <pybind11/functional.h>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM