Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[QUESTION] How to bind NumPy scalar? #3093

Closed
sun1638650145 opened this issue Jul 11, 2021 · 3 comments
Closed

[QUESTION] How to bind NumPy scalar? #3093

sun1638650145 opened this issue Jul 11, 2021 · 3 comments

Comments

@sun1638650145
Copy link

I hope to implement something like this on the Python side.

>>> import numpy as np
>>> from mymodule import print_type
>>> print_type(np.int32(1))
32-bit
>>> print_type(np.int64(1))
64-bit

This way of writing pybind is bound to pure Python int.

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


void print_type(const int &num) {
    std::cout << "32-bit" << std::endl;
    // do something ...
}

void print_type(const std::int64_t &num) {
    std::cout << "64-bit" << std::endl;
    // do something ...
}

PYBIND11_MODULE(mymodule, m) {
    m.def("print_type", pybind11::overload_cast<const int &>(&print_type));
    m.def("print_type", pybind11::overload_cast<const std::int64_t &>(&print_type));
}
@jiwaszki
Copy link
Contributor

Here you go, little tricky but should do the work:

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

void print_type(const pybind11::buffer &num)
{
    auto a = num.request().format;
    if (a == "i")
    {
        std::cout << "32-bit" << std::endl;
        // do something for int...
    }
    else if (a == "l")
    {
        std::cout << "64-bit" << std::endl;
        // do something for std::int64_t...
    }
}

PYBIND11_MODULE(mymodule, m)
{
    m.def("print_type", &print_type);
}

Where to get values for each format? Here: https://docs.python.org/3/library/array.html

The print_type function can later call other specified functions to work on exact buffer values accordingly to dtype. Treat it like a "dispatcher".

@sun1638650145
Copy link
Author

Using your method can indeed solve the problem, thanks. Finally, I hope that pybind can develop functions like this. #2060 (comment) Although your method solves the problem, the type annotation shows buffer instead of int32 or int64.

@jiwaszki
Copy link
Contributor

jiwaszki commented Jul 14, 2021

@sun1638650145 would be nice if that PR was master. Very convenient approach and will resolve your issue with type annotations. Sadly it looks like it is stale or dropped completely...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants