0

How to use functional pointers(C style) with pybind to implement callback functionality.The c++ code has to call the python function . I am encountering errors related to type conversion when trying to use C-style function pointers with Pybind11 for callback functionality.

//cplusplus.cc typedef char* callback_type)(const char* name, const Server* server) class Server{ callback_type server_callback; } char *cplusplus_readfile(const char* name,Server* server) { char *buffer = server->server_callback(name,server); return buffer; // Added return statement } 
//server_test.py import server_wrapper as s BUFFER_LENGTH = 1024 class Test: def server_read(self,name,server): print("Python function called with name:", name) buffer = b'' // do something return buffer def test_func(): server= s.Server() server.register_server_callback(self.cplusplus_readfile) 
// server_wrapper .cc #include <pybind11/pybind11.h> #include <pybind11/embed.h> #include <pybind11/stl.h> #include <pybind11/functional.h> #include <cstring> // Added for strcpy #include "Server.h" namespace py = pybind11; PYBIND11_MODULE(server_wrapper, m) { py::class_<Server>(m, "server") .def(py::init<>()) .def_readwrite("server_callback", &Server::server_callback); .def("register_server_callback", [](py::object &obj,py::function py_callback){ callback_type cb=[py_callback](const char * name , const Server* server) -> char*{ py::object result = py_callback(name,server); std::string str_result = py::str(result); char * buffer = new char[str_result.length()+1]; std::strcpy(buffer,str_result.c_str()); return buffer; }; Server &s = obj.cast<Server>(); s.server_callback=cb; }, "function to set callback"); } 

I am getting the following errors :

..../include/pybind11/detail/../detail/type_caster_base.h:1021:50: error: invalid conversion from 'char* (*)(const char*, const char*)' to 'const void*' [-fpermissive] 1021 | return type_caster_generic::src_and_type(src, cast_type, instance_type); | ^~~ | | | char* (*)(const char*, const char*) ../include/pybind11/detail/../detail/type_caster_base.h:851:30: note: initializing argument 1 of 'static std::pair<const void*, const pybind11::detail::type_info*> pybind11::detail::type_caster_generic::src_and_type(const void*, const std::type_info&, const std::type_info*)' 851 | src_and_type(const void *src, 

using functional pointers( C style ) with pybind

2
  • 1
    You may not assign a capturing closure to a pointer to a function. Commented Feb 23, 2024 at 22:23
  • I did try to remove the capture from the lambda by importing the python module and the function , but still facing similar issues Commented Feb 26, 2024 at 15:30

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.