Commit Graph

250 Commits

Author SHA1 Message Date
Philip Austin 13d8cd2cc7 add the capsule name to the py::capsule constructor
This allows named capsules to be constructed with `py::capsule`.
2017-06-15 10:45:11 -03:00
Jason Rhinelander e45c211497 Support multiple inheritance from python
This commit allows multiple inheritance of pybind11 classes from
Python, e.g.

    class MyType(Base1, Base2):
        def __init__(self):
            Base1.__init__(self)
            Base2.__init__(self)

where Base1 and Base2 are pybind11-exported classes.

This requires collapsing the various builtin base objects
(pybind11_object_56, ...) introduced in 2.1 into a single
pybind11_object of a fixed size; this fixed size object allocates enough
space to contain either a simple object (one base class & small* holder
instance), or a pointer to a new allocation that can contain an
arbitrary number of base classes and holders, with holder size
unrestricted.

* "small" here means having a sizeof() of at most 2 pointers, which is
enough to fit unique_ptr (sizeof is 1 ptr) and shared_ptr (sizeof is 2
ptrs).

To minimize the performance impact, this repurposes
`internals::registered_types_py` to store a vector of pybind-registered
base types.  For direct-use pybind types (e.g. the `PyA` for a C++ `A`)
this is simply storing the same thing as before, but now in a vector;
for Python-side inherited types, the map lets us avoid having to do a
base class traversal as long as we've seen the class before.  The
change to vector is needed for multiple inheritance: Python types
inheriting from multiple registered bases have one entry per base.
2017-06-12 09:56:55 -03:00
Dean Moldovan caedf74a89 Fix py::make_iterator's __next__() for past-the-end calls
Fixes #896.

From Python docs: "Once an iterator’s `__next__()` method raises
`StopIteration`, it must continue to do so on subsequent calls.
Implementations that do not obey this property are deemed broken."
2017-06-10 16:44:21 +02:00
Dean Moldovan 17cc39c818 Don't let pytest discover tests from test_cmake_build and test_embed
pytest raises an error if it recurses into these directories.
2017-06-10 16:44:21 +02:00
Ben Frederickson 74b501cd85 Fix passing in utf8 encoded strings with python 2
Passing utf8 encoded strings from python to a C++ function taking a
std::string was broken.  The previous version was trying to call
'PyUnicode_FromObject' on this data, which failed to convert the string
to unicode with the default ascii codec. Also this incurs an unnecessary
conversion to unicode for data this is immediately converted back to
utf8.

Fix by treating python 2 strings the same python 3 bytes objects, and just
copying over the data if possible.
2017-06-10 10:10:33 -04:00
Dean Moldovan e27ea47c87 Enable detection of private operator new on MSVC
MSVC 2015 Update 3 and 2017 can handle enough expression SFINAE
to make this work now.
2017-06-08 21:54:55 +02:00
Jason Rhinelander 4edb1ce20c Destroy internals if created during Py_Finalize()
Py_Finalize could potentially invoke code that calls `get_internals()`,
which could create a new internals object if one didn't exist.
`finalize_interpreter()` didn't catch this because it only used the
pre-finalize interpreter pointer status; if this happens, it results in
the internals pointer not being properly destroyed with the interpreter,
which leaks, and also causes a `get_internals()` under a future
interpreter to return an internals object that is wrong in various ways.
2017-06-08 16:42:06 -03:00
Dean Moldovan 1d3c4bc54d Fix missing default globals in eval/exec when embedding
Fixes #887.
2017-06-07 11:44:30 +02:00
Jason Rhinelander acedd6c70c std::reference_wrapper: non-generic types; no None
This reimplements the std::reference_wrapper<T> caster to be a shell
around the underlying T caster (rather than assuming T is a generic
type), which lets it work for things like `std::reference_wrapper<int>`
or anything else custom type caster with a lvalue cast operator.

This also makes it properly fail when None is provided, just as an
ordinary lvalue reference argument would similarly fail.

This also adds a static assert to test that T has an appropriate type
caster.  It triggers for casters like `std::pair`, which have
return-by-value cast operators.  (In theory this could be supported by
storing a local temporary for such types, but that's beyond the scope
of this PR).

This also replaces `automatic` or `take_ownership` return value policies
with `automatic_reference` as taking ownership of a reference inside a
reference_wrapper is not valid.
2017-05-30 13:14:49 -04:00
Jason Rhinelander 7cdf9f1a68 Move reference_wrapper test from test_issues to test_python_types
test_issues is deprecated, and the following commit adds other, related
reference_wrapper tests.
2017-05-30 13:14:49 -04:00
Dean Moldovan 005fde6a7f Filter warnings on pytest >= v3.1
The new version of pytest now reports Python warnings by default. This
commit filters out some third-party extension warnings which are not
useful for pybind11 tests.
2017-05-30 18:56:10 +02:00
Dean Moldovan 443ab5946b Replace PYBIND11_PLUGIN with PYBIND11_MODULE
This commit also adds `doc()` to `object_api` as a shortcut for the
`attr("__doc__")` accessor.

The module macro changes from:
```c++
PYBIND11_PLUGIN(example) {
    pybind11::module m("example", "pybind11 example plugin");
    m.def("add", [](int a, int b) { return a + b; });
    return m.ptr();
}
```

to:

```c++
PYBIND11_MODULE(example, m) {
    m.doc() = "pybind11 example plugin";
    m.def("add", [](int a, int b) { return a + b; });
}
```

Using the old macro results in a deprecation warning. The warning
actually points to the `pybind11_init` function (since attributes
don't bind to macros), but the message should be quite clear:
"PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE".
2017-05-29 03:21:19 +02:00
Yannick Jadoul b700c5d672 Convenience constructor templates for buffer_info (#860)
* Added template constructors to buffer_info that can deduce the item size, format string, and number of dimensions from the pointer type and the shape container

* Implemented actual buffer_info constructor as private delegate constructor taking rvalue reference as a workaround for the evaluation order move problem on GCC 4.8
2017-05-29 03:13:55 +02:00
Dean Moldovan 427e4afc69 Fix buffer protocol inheritance
Fixes #878.
2017-05-29 02:03:58 +02:00
Dean Moldovan 931b9e93ab Support restarting the interpreter and subinterpreters 2017-05-28 02:12:24 +02:00
Dean Moldovan 22c413b196 Add C++ interface for the Python interpreter 2017-05-28 02:12:24 +02:00
Dean Moldovan 9693a5c78f Add Catch framework for testing embedding support and C++-side features
At this point, there is only a single test for interpreter basics.

Apart from embedding itself, having a C++ test framework will also
benefit the C++-side features by allowing them to be tested directly.
2017-05-28 02:12:24 +02:00
Dean Moldovan 7f5c85c861 Add CMake target for embedding the Python interpreter
All targets provided by pybind11:

* pybind11::module - the existing target for creating extension modules
* pybind11::embed - new target for embedding the interpreter
* pybind11::pybind11 - common "base" target (headers only)
2017-05-28 02:12:24 +02:00
Bruce Merry 46dbee7d42 Avoid explicitly resetting a std::[experimental::]optional
Now that #851 has removed all multiple uses of a caster, it can just use
the default-constructed value with needing a reset. This fixes two
issues:

1. With std::experimental::optional (at least under GCC 5.4), the `= {}`
would construct an instance of the optional type and then move-assign
it, which fails if the value type isn't move-assignable.

2. With older versions of Boost, the `= {}` could fail because it is
ambiguous, allowing construction of either `boost::none` or the value
type.
2017-05-27 23:52:23 +02:00
Bruce Merry eee4f4fc7e Fix invalid memory access in vector insert method
The stl_bind.h wrapper for `Vector.insert` neglected to do a bounds
check.
2017-05-25 10:51:28 -04:00
Jason Rhinelander 8dc63ba941 Force MSVC to compile in utf-8 mode
MSVC by default uses the local codepage, which fails when it sees the
utf-8 in test_python_types.cpp.  This adds the /utf-8 flag to the test
suite compilation to force it to interpret source code as utf-8.

Fixes #869
2017-05-25 10:09:56 -04:00
Jason Rhinelander f3ce00eaed vectorize: pass-through of non-vectorizable args
This extends py::vectorize to automatically pass through
non-vectorizable arguments.  This removes the need for the documented
"explicitly exclude an argument" workaround.

Vectorization now applies to arithmetic, std::complex, and POD types,
passed as plain value or by const lvalue reference (previously only
pass-by-value types were supported).  Non-const lvalue references and
any other types are passed through as-is.

Functions with rvalue reference arguments (whether vectorizable or not)
are explicitly prohibited: an rvalue reference is inherently not
something that can be passed multiple times and is thus unsuitable to
being in a vectorized function.

The vectorize returned value is also now more sensitive to inputs:
previously it would return by value when all inputs are of size 1; this
is now amended to having all inputs of size 1 *and* 0 dimensions.  Thus
if you pass in, for example, [[1]], you get back a 1x1, 2D array, while
previously you got back just the resulting single value.

Vectorization of member function specializations is now also supported
via `py::vectorize(&Class::method)`; this required passthrough support
for the initial object pointer on the wrapping function pointer.
2017-05-24 20:43:41 -04:00
Jason Rhinelander 4e1e4a580e Allow py::arg().none(false) argument attribute
This attribute lets you disable (or explicitly enable) passing None to
an argument that otherwise would allow it by accepting
a value by raw pointer or shared_ptr.
2017-05-24 13:10:57 -04:00
Jason Rhinelander 813d7e8687 Add movable cast support to type casters
This commit allows type_casters to allow their local values to be moved
away, rather than copied, when the type caster instance itself is an rvalue.

This only applies (automatically) to type casters using
PYBIND11_TYPE_CASTER; the generic type type casters don't own their own
pointer, and various value casters (e.g. std::string, std::pair,
arithmetic types) already cast to an rvalue (i.e. they return by value).

This updates various calling code to attempt to get a movable value
whenever the value is itself coming from a type caster about to be
destroyed: for example, when constructing an std::pair or various stl.h
containers.  For types that don't support value moving, the cast_op
falls back to an lvalue cast.

There wasn't an obvious place to add the tests, so I added them to
test_copy_move_policies, but also renamed it to drop the _policies as it
now tests more than just policies.
2017-05-24 13:09:31 -04:00
Bruce Merry fe0cf8b73b Support pointers to member functions in def_buffer.
Closes #857, by adding overloads to def_buffer that match pointers to
member functions and wrap them in lambdas.
2017-05-22 17:53:37 -04:00
Jason Rhinelander b8ac438386 Use dynamic cast for shared_from_this holder init
Using a dynamic_cast instead of a static_cast is needed to safely cast
from a base to a derived type.  The previous static_pointer_cast isn't
safe, however, when downcasting (and fails to compile when downcasting
with virtual inheritance).

Switching this to always use a dynamic_pointer_cast shouldn't incur any
additional overhead when a static_pointer_cast is safe (i.e. when
upcasting, or self-casting): compilers don't need RTTI checks in those
cases.
2017-05-22 11:43:21 -04:00
Jason Rhinelander acad05cb13 Fix /= operator under Python 3
The Python method for /= was set as `__idiv__`, which should be
`__itruediv__` under Python 3.

This wasn't totally broken in that without it defined, Python constructs
a new object by calling __truediv__.  The operator tests, however,
didn't actually test the /= operator: when I added it, I saw an extra
construction, leading to the problem.  This commit also includes tests
for the previously untested *= operator, and adds some element-wise
vector multiplication and division operators.
2017-05-21 19:15:25 -04:00
Dean Moldovan 4567f1f82a Fix Eigen shape assertion error in dense matrix caster
Missing conformability check was causing Eigen to create a 0x0 matrix
with an error in debug mode and silent corruption in release mode.
2017-05-11 16:10:40 +02:00
Dean Moldovan 94d0a9f7bc Improve constructor resolution in variant_caster
Currently, `py::int_(1).cast<variant<double, int>>()` fills the `double`
slot of the variant. This commit switches the loader to a 2-pass scheme
in order to correctly fill the `int` slot.
2017-05-10 17:47:57 +02:00
Jason Rhinelander 93e3eac6f9 Defer None loading to second pass
Many of our `is_none()` checks in type caster loading return true, but
this should really be considered a deferral so that, for example, an
overload with a `py::none` argument would win over one that takes
`py::none` as a null option.

This keeps None-accepting for the `!convert` pass only for std::optional
and void casters.  (The `char` caster already deferred None; this just
extends that behaviour to other casters).
2017-05-10 10:44:19 -04:00
Bruce Merry b82c0f0a2d Allow std::complex field with PYBIND11_NUMPY_DTYPE (#831)
This exposed a few underlying issues:

1. is_pod_struct was too strict to allow this. I've relaxed it to
require only trivially copyable and standard layout, rather than POD
(which additionally requires a trivial constructor, which std::complex
violates).

2. format_descriptor<std::complex<T>>::format() returned numpy format
strings instead of PEP3118 format strings, but register_dtype
feeds format codes of its fields to _dtype_from_pep3118. I've changed it
to return PEP3118 format codes. format_descriptor is a public type, so
this may be considered an incompatible change.

3. register_structured_dtype tried to be smart about whether to mark
fields as unaligned (with ^). However, it's examining the C++ alignment,
rather than what numpy (or possibly PEP3118) thinks the alignment should
be. For complex values those are different. I've made it mark all fields
as ^ unconditionally, which should always be safe even if they are
aligned, because we explicitly mark the padding.
2017-05-10 11:36:24 +02:00
Bruce Merry 8e0d832c7d Support arrays inside PYBIND11_NUMPY_DTYPE (#832)
Resolves #800.

Both C++ arrays and std::array are supported, including mixtures like
std::array<int, 2>[4]. In a multi-dimensional array of char, the last
dimension is used to construct a numpy string type.
2017-05-10 10:21:01 +02:00
Dean Moldovan 78f1dcf98f Fix std::nullptr_t caster (#840)
* Fix compilation error with std::nullptr_t

* Enable conversion from None to std::nullptr_t and std::nullopt_t

Fixes #839.
2017-05-09 23:30:05 +02:00
Dean Moldovan 076c738641 Add py::exec() as a shortcut for py::eval<py::eval_statements>() 2017-05-08 20:46:16 +02:00
Dean Moldovan 36f0a15a49 Deprecate handle::operator== in favor of object_api::is 2017-05-08 01:53:07 +02:00
Cris Luengo 30d43c4992 Now `shape`, `size`, `ndims` and `itemsize` are also signed integers. 2017-05-08 01:50:21 +02:00
Jason Rhinelander b68959e822 Use numpy rather than Eigen for copying
We're current copy by creating an Eigen::Map into the input numpy
array, then assigning that to the basic eigen type, effectively having
Eigen do the copy.  That doesn't work for negative strides, though:
Eigen doesn't allow them.

This commit makes numpy do the copying instead by allocating the eigen
type, then having numpy copy from the input array into a numpy reference
into the eigen object's data.  This also saves a copy when type
conversion is required: numpy can do the conversion on-the-fly as part
of the copy.

Finally this commit also makes non-reference parameters respect the
convert flag, declining the load when called in a noconvert pass with a
convertible, but non-array input or an array with the wrong dtype.
2017-05-08 01:50:21 +02:00
Cris Luengo 627da3f135 Making a copy when casting a numpy array with negative strides to Eigen.
`EigenConformable::stride_compatible` returns false if the strides are
negative. In this case, do not use `EigenConformable::stride`, as it
is {0,0}. We cannot write negative strides in this element, as Eigen
will throw an assertion if we do.

The `type_caster` specialization for regular, dense Eigen matrices now
does a second `array_t::ensure` to copy data in case of negative strides.
I'm not sure that this is the best way to implement this.

I have added "TODO" tags linking these changes to Eigen bug #747, which,
when fixed, will allow Eigen to accept negative strides.
2017-05-08 01:50:21 +02:00
Cris Luengo d400f60c96 Python buffer objects can have negative strides. 2017-05-08 01:50:21 +02:00
Jason Rhinelander 271b27ff18 Remove obsolete comment 2017-05-02 15:21:39 -04:00
uentity 083a0219b5 array: implement array resize 2017-04-29 15:19:45 -04:00
Dean Moldovan 4ffa76ec56 Add type caster for std::variant and other variant-like classes 2017-04-29 17:31:30 +02:00
Jason Rhinelander a01b6b805c functional: support bound methods
If a bound std::function is invoked with a bound method, the implicit
bound self is lost because we use `detail::get_function` to unbox the
function.  This commit amends the code to use py::function and only
unboxes in the special is-really-a-c-function case.  This makes bound
methods stay bound rather than unbinding them by forcing extraction of
the c function.
2017-04-29 10:43:17 -04:00
Wenzel Jakob 7653a115bd pytest target: add USE_TERMINAL flag
The added flag enables non-buffered console output when using Ninja
2017-04-29 16:35:28 +02:00
Wenzel Jakob e6fd2cd5ab enum_: fix implicit conversion on Python 2.7
Enumerations on Python 2.7 were not always implicitly converted to
integers (depending on the target size). This patch adds a __long__
conversion function (only enabled on 2.7) which fixes this issue.

The attached test case fails without this patch.
2017-04-29 16:35:28 +02:00
Jason Rhinelander 51d18aa252 Fix ambiguous initialize_list arguments
This removes the convert-from-arithemtic-scalar constructor of
any_container as it can result in ambiguous calls, as in:

    py::array_t<float>({ 1, 2 })

which could be intepreted as either of:

    py::array_t<float>(py::array_t<float>(1, 2))
    py::array_t<float>(py::detail::any_container({ 1, 2 }))

Removing the convert-from-arithmetic constructor reduces the number of
implicit conversions, avoiding the ambiguity for array and array_t.
This also re-adds the array/array_t constructors taking a scalar
argument for backwards compatibility.
2017-04-28 14:12:06 -04:00
Jason Rhinelander 0a90b2db71 Don't let PyInstanceMethod hide itself
Python 3's `PyInstanceMethod_Type` hides itself via its `tp_descr_get`,
which prevents aliasing methods via `cls.attr("m2") = cls.attr("m1")`:
instead the `tp_descr_get` returns a plain function, when called on a
class, or a `PyMethod`, when called on an instance.  Override that
behaviour for pybind11 types with a special bypass for
`PyInstanceMethod_Types`.
2017-04-28 11:18:58 -04:00
Jason Rhinelander a7f704b39b Fix Python 3 `bytes` conversion to std::string/char*
The Unicode support added in 2.1 (PR #624) inadvertently broke accepting
`bytes` as std::string/char* arguments.  This restores it with a
separate path that does a plain conversion (i.e. completely bypassing
all the encoding/decoding code), but only for single-byte string types.
2017-04-28 11:14:14 -04:00
Jason Rhinelander 1f8a100d38 Track base class pointers of instances
This commits adds base class pointers of offset base classes (i.e. due
to multiple inheritance) to `registered_instances` so that if such a
pointer is returned we properly recognize it as an existing instance.

Without this, returning a base class pointer will cast to the existing
instance if the pointer happens to coincide with the instance pointer,
but constructs a new instance (quite possibly with a segfault, if
ownership is applied) for unequal base class pointers due to multiple
inheritance.
2017-04-27 09:12:41 -04:00
Jason Rhinelander 14e70650fe Fix downcasting of base class pointers
When we are returned a base class pointer (either directly or via
shared_from_this()) we detect its runtime type (using `typeid`), then
end up essentially reinterpret_casting the pointer to the derived type.
This is invalid when the base class pointer was a non-first base, and we
end up with an invalid pointer.  We could dynamic_cast to the
most-derived type, but if *that* type isn't pybind11-registered, the
resulting pointer given to the base `cast` implementation isn't necessarily valid
to be reinterpret_cast'ed back to the backup type.

This commit removes the "backup" type argument from the many-argument
`cast(...)` and instead does the derived-or-pointer type decision and
type lookup in type_caster_base, where the dynamic_cast has to be to
correctly get the derived pointer, but also has to do the type lookup to
ensure that we don't pass the wrong (derived) pointer when the backup
type (i.e. the type caster intrinsic type) pointer is needed.

Since the lookup is needed before calling the base cast(), this also
changes the input type to a detail::type_info rather than doing a
(second) lookup in cast().
2017-04-27 09:12:41 -04:00