logo
down
shadow

Wrapping variadic templates in pybind11


Wrapping variadic templates in pybind11

By : Dina
Date : November 16 2020, 04:01 AM
may help you . Mixing templates and Python is best done at run-time to make sure you have all template instantiations that will actually be used. You can do that with cppyy (http://cppyy.org), which uses Cling (LLVM) underneath to instantiate the templates.
Using your example (with cerr replacing your LOG, the specific code for which you did not post):
code :
import cppyy

# variadic template example; the code can also live in a header which is loaded 
# with "cppyy.include()"
cppyy.cppdef(r"""
    template <typename Arg, typename... Args>
    void log(int level, Arg&& arg, Args&&... args)
    {   
        std::stringstream out;
        out << std::forward<Arg>(arg);
        using expander = int[];
        (void)expander{0, (void(out << ' ' << std::forward<Args>(args)), 0)...};
        std::cerr << out.str() << '\n';
    }
""")

level = 1
cppyy.gbl.log(level, 1, "string", 3.14)
1 string 3.14


Share : facebook icon twitter icon
Wrapping STL container return types using Pybind11

Wrapping STL container return types using Pybind11


By : 9r6i7kr6
Date : March 29 2020, 07:55 AM
I hope this helps . The problem might be with the PYBIND11_MAKE_OPAQUE treatment of the ArrayComplex4 data structure, I couldn't get this to work, although I'll look at it some more when I get time.
The following code, which I did get to work, is my closest approximation so far to your design. I used an additional user-defined data structure to wrap the std:: elements:
code :
#include <pybind11/pybind11.h>
#include <pybind11/complex.h>
#include <pybind11/stl.h>
#include <memory>
#include <complex>
#include <array>
#include <cmath>

namespace py = pybind11;


typedef std::array<std::complex<double>, 4> ArrayComplex4;

struct ArrayComplex4Holder
{
    ArrayComplex4 data;
    ArrayComplex4 getData() { return data; }
};

class MyClass {
public:
    MyClass() { }
    std::unique_ptr<ArrayComplex4Holder> my_function(double x)
    {
        std::unique_ptr<ArrayComplex4Holder> ph( new ArrayComplex4Holder());
        ph->data[0] = std::complex<double>(x);
        return ph;
    }
    std::unique_ptr<ArrayComplex4Holder> my_function(double x, double y)
    {
        std::unique_ptr<ArrayComplex4Holder> ph( new ArrayComplex4Holder());
        ph->data[0] = std::complex<double>(x);
        ph->data[1] = std::complex<double>(y);
        return ph;
    }
};

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

    py::class_<ArrayComplex4Holder>(m, "ArrayComplex4Holder")
            .def(py::init<>())
            .def("getData", &ArrayComplex4Holder::getData);

    py::class_<MyClass>(m, "MyClass")
            .def(py::init<>())
            .def("my_function", (std::unique_ptr<ArrayComplex4Holder> (MyClass::*)(double))         &MyClass::my_function)
            .def("my_function", (std::unique_ptr<ArrayComplex4Holder> (MyClass::*)(double, double)) &MyClass::my_function);
}
import sys
sys.path.append('/Volumes/RAID 1/Projects/workspace/Project CPP 1')
import example

p = example.MyClass()
print (p.my_function(1.2345).getData())
print (p.my_function(1.2345, 6.7890).getData())
[(1.2345+0j), 0j, 0j, 0j]
[(1.2345+0j), (6.789+0j), 0j, 0j]
Why only C++(and D language) provides variadic templates feature? Are variadic templates that good?

Why only C++(and D language) provides variadic templates feature? Are variadic templates that good?


By : masi
Date : March 29 2020, 07:55 AM
hope this fix your issue Common Lisp provides much better than variadic templates thru its macro system (beware, Lisp macros are much more powerful than C++ templates or macros for its preprocessor). Lisp predates C++ (and C) by decades! Try SBCL (a freely available excellent Common Lisp implementation).
BTW, I think that D and Terra and Template Haskell also have something similar to variadic templates, and probably other languages too .... I cannot explain why Lisp ideas vanished, the reasons are more sociological, educational and economical than technical; read also SICP, Practical Common Lisp and Lisp In Small Pieces.
pybind11 wrapping existing code

pybind11 wrapping existing code


By : mathaig
Date : March 29 2020, 07:55 AM
like below fixes the issue Despite serving the same purpose, SWIG and Pybind11 are different tools.
As the name implies, SWIG (Simplified Wrapper and Interface Generator) is a generator tool that create Python binding for existing C++ code, using definitions written in a special language.
Wrapping C++ void functions with pybind11

Wrapping C++ void functions with pybind11


By : josher GT
Date : March 29 2020, 07:55 AM
wish of those help Including pybind11/stl.h results to copy-conversions between c++ and pyhton, see http://pybind11.readthedocs.io/en/stable/advanced/cast/stl.html#automatic-conversion
To pass by reference see section http://pybind11.readthedocs.io/en/stable/advanced/cast/stl.html#making-opaque-types
Wrapping a C++ allocated instance with pybind11

Wrapping a C++ allocated instance with pybind11


By : Allen Kao
Date : September 30 2020, 11:00 AM
To fix the issue you can do If you check the resulting py::object from the cast (e.g. by casting it to bool), you will see that the call failed. The reason is that the python does not know the class "Pet" (nor shared_ptr). You can either use the code as above and create a module from it the usual way, then import that in a main program. Or, use the EMBEDDED_MODULE feature, which is closer to what you appear to be going for.
Adjusting your example:
code :
#include <stdio.h>
#include <pybind11/pybind11.h>
#include <pybind11/embed.h>

using namespace std;
namespace py = pybind11;

class Pet
{
public:
    Pet() {}
    void bark(void) { printf("wow!\n"); }
};

PYBIND11_EMBEDDED_MODULE(Pets, m) {
    py::class_<Pet, shared_ptr<Pet>>(m, "Pet")
        .def("bark", &Pet::bark)
    ;
}

int main(int argc, char *argv[])
{
  py::scoped_interpreter guard{};
  shared_ptr<Pet> pet = make_shared<Pet>();

  auto pets_mod = py::module::import("Pets");

  py::globals()["pet"] = py::cast(pet);
  py::exec("pet.bark()\n");
}
Related Posts Related Posts :
  • C++ on Vistual Studio with CMake error: manifest 'build.ninja' still dirty after 100 tries
  • Is there a way to automatically resolve an overloaded method via a template parameter?
  • Fastest way to find pair in a vector, remove it while iterating
  • error C2440: '=': cannot convert from 'const char *' to 'LPCWSTR'
  • Unable to call boost::clear_vertex while using listS for the vertex and edge lists
  • Decoding binary data from serial port
  • Pattern to Implement an OO interface to a C program written in an imperative style
  • CEPH + Librados++ is not returning consisten results
  • `LoadLibraryExW` triggers exception `0xC0000023` from `NtMapViewOfSection`
  • static_cast to a struct type to access all of its member variable
  • Forward declaration for boost::intrusive_ptr class to reduce compile time
  • How to use priority_queue with a non-static compare method of class instance?
  • Template parameters inside and outside class/struct
  • Determining prime number
  • How to resolve ambiguity between constructors taking std::string and std::vector
  • My program crashes when I try to change private values from an object
  • Unordered_map with custom class as key
  • Strict aliasing rules broken with templates and inheritance
  • C++ Derived Class Override Return Type
  • singly linked list c++ constructor, destructor and printing out
  • How to clone class with vector of unique_ptr to base class
  • error: no match for operator
  • std::vector doesnt accept my struct as template
  • selection of people's contours
  • how to fix the (Error using mexOpenCV) on matlab?
  • Is or was there a proposal for c++ to use the context for short enum values?
  • Fair assumptions about std::hash implementations
  • undefined reference to libusb using cyusb
  • Function returns null pointer instead of address
  • C++17 copy elision and object destruction
  • Input multiple strings via operator>> c++
  • Avoiding overflow boost container
  • How to Write a Lambda Wrapping a Function with Optional Return Value
  • Partial specialization with more template parameters
  • How to convert fixed size array to pointer on pointer array
  • Memory leak in const member constructor with tag dispatching
  • C++ function with a generic and optional class
  • Custom QGraphicsItem That Contains Child QGraphicsItems
  • Are There Restrictions on What can be Passed to auto Template Parameters?
  • Rotating line inside rectangle bounds
  • Why do I need dynamic memory allocation if I can just create an array?
  • How can I convert a text file into a form that MPI_Bcast can send?
  • How to get array of all `this` of an instance
  • Using pointers as parameters
  • Automatic type deduction with const_cast is not working
  • Why does std::is_rvalue_reference not do what it is advertised to do?
  • Function Template Specialization with Forward Declared Type
  • template deduction failed in vector
  • Is there a signed `sizeof` alternative in Qt
  • clarification on overloading the -> operator
  • What is __m128d?
  • QtConcurrent: why releaseThread and reserveThread cause deadlock?
  • Function receiving different value than passed
  • Can C++ close a '''fstream''' variable after '''.close()'''?
  • Is it necessary to overload operator in this specific case
  • Comparing an element of a string array with a string
  • how to dereference a pointer of a map of pointers to objects in c++
  • How recursive function control flow change for static variable?
  • SDL 2 blitting BMP File
  • Why does an extremely large value cause this code to repeat infinitely?
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org