Commit Graph

293 Commits

Author SHA1 Message Date
Dean Moldovan b33475d054 Speed up AppVeyor build (#1021)
The `latest` build remains as is, but all others are modified to:

* Use regular Python instead of conda. `pip install` is much faster
  than conda, but scipy isn't available. Numpy is still tested.

* Compile in debug mode instead of release.

* Skip CMake build tests. For some reason, CMake configuration is very
  slow on AppVeyor and these tests are almost entirely CMake.

The changes reduce build time to about 1/3 of the original. The `latest` 
config still covers scipy, release mode and the CMake build tests, so 
the others don't need to.
2017-08-23 17:18:57 +02:00
Wenzel Jakob 4336a7da4a support for brace initialization 2017-08-22 16:22:56 +02:00
Dean Moldovan 234f7c39a0 Test and document binding protected member functions 2017-08-22 12:42:27 +02:00
Jason Rhinelander 5e14aa6aa7 Allow module-local classes to be loaded externally
The main point of `py::module_local` is to make the C++ -> Python cast
unique so that returning/casting a C++ instance is well-defined.
Unfortunately it also makes loading unique, but this isn't particularly
desirable: when an instance contains `Type` instance there's no reason
it shouldn't be possible to pass that instance to a bound function
taking a `Type` parameter, even if that function is in another module.

This commit solves the issue by allowing foreign module (and global)
type loaders have a chance to load the value if the local module loader
fails.  The implementation here does this by storing a module-local
loading function in a capsule in the python type, which we can then call
if the local (and possibly global, if the local type is masking a global
type) version doesn't work.
2017-08-19 15:30:39 -04:00
Jason Rhinelander c4e180081d Reimplement py::init<...> to use common factory code
This reimplements the py::init<...> implementations using the various
functions added to support `py::init(...)`, and moves the implementing
structs into `detail/init.h` from `pybind11.h`.  It doesn't simply use a
factory directly, as this is a very common case and implementation
without an extra lambda call is a small but useful optimization.

This, combined with the previous lazy initialization, also avoids
needing placement new for `py::init<...>()` construction: such
construction now occurs via an ordinary `new Type(...)`.

A consequence of this is that it also fixes a potential bug when using
multiple inheritance from Python: it was very easy to write classes
that double-initialize an existing instance which had the potential to
leak for non-pod classes.  With the new implementation, an attempt to
call `__init__` on an already-initialized object is now ignored.  (This
was already done in the previous commit for factory constructors).

This change exposed a few warnings (fixed here) from deleting a pointer
to a base class with virtual functions but without a virtual destructor.
These look like legitimate warnings that we shouldn't suppress; this
adds virtual destructors to the appropriate classes.
2017-08-17 09:33:27 -04:00
Jason Rhinelander 464d98962d Allow binding factory functions as constructors
This allows you to use:

    cls.def(py::init(&factory_function));

where `factory_function` returns a pointer, holder, or value of the
class type (or a derived type).  Various compile-time checks
(static_asserts) are performed to ensure the function is valid, and
various run-time type checks where necessary.

Some other details of this feature:
- The `py::init` name doesn't conflict with the templated no-argument
  `py::init<...>()`, but keeps the naming consistent: the existing
  templated, no-argument one wraps constructors, the no-template,
  function-argument one wraps factory functions.
- If returning a CppClass (whether by value or pointer) when an CppAlias
  is required (i.e. python-side inheritance and a declared alias), a
  dynamic_cast to the alias is attempted (for the pointer version); if
  it fails, or if returned by value, an Alias(Class &&) constructor
  is invoked.  If this constructor doesn't exist, a runtime error occurs.
- for holder returns when an alias is required, we try a dynamic_cast of
  the wrapped pointer to the alias to see if it is already an alias
  instance; if it isn't, we raise an error.
- `py::init(class_factory, alias_factory)` is also available that takes
  two factories: the first is called when an alias is not needed, the
  second when it is.
- Reimplement factory instance clearing.  The previous implementation
  failed under python-side multiple inheritance: *each* inherited
  type's factory init would clear the instance instead of only setting
  its own type value.  The new implementation here clears just the
  relevant value pointer.
- dealloc is updated to explicitly set the leftover value pointer to
  nullptr and the `holder_constructed` flag to false so that it can be
  used to clear preallocated value without needing to rebuild the
  instance internals data.
- Added various tests to test out new allocation/deallocation code.
- With preallocation now done lazily, init factory holders can
  completely avoid the extra overhead of needing an extra
  allocation/deallocation.
- Updated documentation to make factory constructors the default
  advanced constructor style.
- If an `__init__` is called a second time, we have two choices: we can
  throw away the first instance, replacing it with the second; or we can
  ignore the second call.  The latter is slightly easier, so do that.
2017-08-17 09:33:27 -04:00
Jason Rhinelander 42e5ddc541 Add a polymorphic static assert when using an alias
An alias can be used for two main purposes: to override virtual methods,
and to add some extra data to a class needed for the pybind-wrapper.
Both of these absolutely require that the wrapped class be polymorphic
so that virtual dispatch and destruction, respectively, works.
2017-08-17 09:33:27 -04:00
Dean Moldovan 8d3cedbe2b Add test for mixing STL casters and local binders across modules
One module uses a generic vector caster from `<pybind11/stl.h>` while
the other exports `std::vector<int>` with a local `py:bind_vector`.
2017-08-14 01:11:52 +02:00
Dean Moldovan 7918bcc95b Add support for boost::variant in C++11 mode
In C++11 mode, `boost::apply_visitor` requires an explicit `result_type`.
This also adds optional tests for `boost::variant` in C++11/14, if boost
is available. In C++17 mode, `std::variant` is tested instead.
2017-08-12 21:27:44 +02:00
Dean Moldovan 3dde6ddc53 Add test for custom CMake export group 2017-08-07 23:08:20 +02:00
Jason Rhinelander 391c75447d Update all remaining tests to new test styles
This udpates all the remaining tests to the new test suite code and
comment styles started in #898.  For the most part, the test coverage
here is unchanged, with a few minor exceptions as noted below.

- test_constants_and_functions: this adds more overload tests with
  overloads with different number of arguments for more comprehensive
  overload_cast testing.  The test style conversion broke the overload
  tests under MSVC 2015, prompting the additional tests while looking
  for a workaround.

- test_eigen: this dropped the unused functions `get_cm_corners` and
  `get_cm_corners_const`--these same tests were duplicates of the same
  things provided (and used) via ReturnTester methods.

- test_opaque_types: this test had a hidden dependence on ExampleMandA
  which is now fixed by using the global UserType which suffices for the
  relevant test.

- test_methods_and_attributes: this required some additions to UserType
  to make it usable as a replacement for the test's previous SimpleType:
  UserType gained a value mutator, and the `value` property is not
  mutable (it was previously readonly).  Some overload tests were also
  added to better test overload_cast (as described above).

- test_numpy_array: removed the untemplated mutate_data/mutate_data_t:
  the templated versions with an empty parameter pack expand to the same
  thing.

- test_stl: this was already mostly in the new style; this just tweaks
  things a bit, localizing a class, and adding some missing
  `// test_whatever` comments.

- test_virtual_functions: like `test_stl`, this was mostly in the new
  test style already, but needed some `// test_whatever` comments.
  This commit also moves the inherited virtual example code to the end
  of the file, after the main set of tests (since it is less important
  than the other tests, and rather length); it also got renamed to
  `test_inherited_virtuals` (from `test_inheriting_repeat`) because it
  tests both inherited virtual approaches, not just the repeat approach.
2017-08-05 18:46:22 -04:00
Jason Rhinelander 9866a0f994 test_class: use gc_collect instead of detail_reg_inst side-effect 2017-08-05 18:46:22 -04:00
Jason Rhinelander b468a3cefc Ignore undefined name `long` errors on Python 3 2017-08-05 18:46:22 -04:00
Jason Rhinelander 4b159230d9 Made module_local types take precedence over global types
Attempting to mix py::module_local and non-module_local classes results
in some unexpected/undesirable behaviour:

- if a class is registered non-local by some other module, a later
  attempt to register it locally fails.  It doesn't need to: it is
  perfectly acceptable for the local registration to simply override
  the external global registration.
- going the other way (i.e. module `A` registers a type `T` locally,
  then `B` registers the same type `T` globally) causes a more serious
  issue: `A.T`'s constructors no longer work because the `self` argument
  gets converted to a `B.T`, which then fails to resolve.

Changing the cast precedence to prefer local over global fixes this and
makes it work more consistently, regardless of module load order.
2017-08-05 11:23:34 -04:00
Jason Rhinelander 7437c69500 Add py::module_local() attribute for module-local type bindings
This commit adds a `py::module_local` attribute that lets you confine a
registered type to the module (more technically, the shared object) in
which it is defined, by registering it with:

    py::class_<C>(m, "C", py::module_local())

This will allow the same C++ class `C` to be registered in different
modules with independent sets of class definitions.  On the Python side,
two such types will be completely distinct; on the C++ side, the C++
type resolves to a different Python type in each module.

This applies `py::module_local` automatically to `stl_bind.h` bindings
when the container value type looks like something global: i.e. when it
is a converting type (for example, when binding a `std::vector<int>`),
or when it is a registered type itself bound with `py::module_local`.
This should help resolve potential future conflicts (e.g. if two
completely unrelated modules both try to bind a `std::vector<int>`.
Users can override the automatic selection by adding a
`py::module_local()` or `py::module_local(false)`.

Note that this does mildly break backwards compatibility: bound stl
containers of basic types like `std::vector<int>` cannot be bound in one
module and returned in a different module.  (This can be re-enabled with
`py::module_local(false)` as described above, but with the potential for
eventual load conflicts).
2017-08-04 10:47:34 -04:00
Jason Rhinelander d598172993 Fix builtin exception handlers to work across modules
The builtin exception handler currently doesn't work across modules
under clang/libc++ for builtin pybind exceptions like
`pybind11::error_already_set` or `pybind11::stop_iteration`: under
RTLD_LOCAL module loading clang considers each module's exception
classes distinct types.  This then means that the base exception
translator fails to catch the exceptions and the fall through to the
generic `std::exception` handler, which completely breaks things like
`stop_iteration`: only the `stop_iteration` of the first module loaded
actually works properly; later modules raise a RuntimeError with no
message when trying to invoke their iterators.

For example, two modules defined like this exhibit the behaviour under
clang++/libc++:

z1.cpp:
    #include <pybind11/pybind11.h>
    #include <pybind11/stl_bind.h>
    namespace py = pybind11;
    PYBIND11_MODULE(z1, m) {
        py::bind_vector<std::vector<long>>(m, "IntVector");
    }

z2.cpp:
    #include <pybind11/pybind11.h>
    #include <pybind11/stl_bind.h>
    namespace py = pybind11;
    PYBIND11_MODULE(z2, m) {
        py::bind_vector<std::vector<double>>(m, "FloatVector");
    }

Python:
    import z1, z2
    for i in z2.FloatVector():
        pass

results in:
    Traceback (most recent call last):
      File "zs.py", line 2, in <module>
        for i in z2.FloatVector():
    RuntimeError

This commit fixes the issue by adding a new exception translator each
time the internals pointer is initialized from python builtins: this
generally means the internals data was initialized by some other
module.  (The extra translator(s) are skipped under libstdc++).
2017-08-04 10:47:34 -04:00
Jason Rhinelander 0bd5979c77 Add cross-module test plugin
This adds the infrastructure for a separate test plugin for cross-module
tests.  (This commit contains no tests that actually use it, but the
following commits do; this is separated simply to provide a cleaner
commit history).
2017-08-04 10:47:34 -04:00
Jason Rhinelander 373da82486 Make PYBIND11_OBJECT_CVT only convert if the type check fails
Currently types that are capable of conversion always call their convert
function when invoked with a `py::object` which is actually the correct
type.  This means that code such as `py::cast<py::list>(obj)` and
`py::list l(obj.attr("list"))` make copies, which was an oversight
rather than an intentional feature.

While at first glance there might be something behind having
`py::list(obj)` make a copy (as it would in Python), this would be
inconsistent when you dig a little deeper because `py::list(l)`
*doesn't* make a copy for an existing `py::list l`, and having an
inconsistency within C++ would be worse than a C++ <-> Python
inconsistency.

It is possible to get around the copying using a
`reinterpret_borrow<list>(o)` (and this commit fixes one place, in
`embed.h`, that does so), but that seems a misuse of
`reinterpret_borrow`, which is really supposed to be just for dealing
with raw python-returned values, not `py::object`-derived wrappers which
are supposed to be higher level.

This changes the constructor of such converting types (i.e. anything
using PYBIND11_OBJECT_CVT -- `str`, `bool_`, `int_`, `float_`, `tuple`,
`dict`, `list`, `set`, `memoryview`) to reference rather than copy when
the check function passes.

It also adds an `object &&` constructor that is slightly more efficient
by avoiding an inc_ref when the check function passes.
2017-08-04 10:14:55 -04:00
Jason Rhinelander 85d63c3bcd Superclass typo fix
This didn't actually affect anything (because all the MI3 constructor
does is invoke MI2 with the same arguments anyway).
2017-07-29 03:54:25 -04:00
Jason Rhinelander 1682b67326 Simplify error_already_set
`error_already_set` is more complicated than it needs to be, partly
because it manages reference counts itself rather than using
`py::object`, and partly because it tries to do more exception clearing
than is needed.  This commit greatly simplifies it, and fixes #927.

Using `py::object` instead of `PyObject *` means we can rely on
implicit copy/move constructors.

The current logic did both a `PyErr_Clear` on deletion *and* a
`PyErr_Fetch` on creation.  I can't see how the `PyErr_Clear` on
deletion is ever useful: the `Fetch` on creation itself clears the
error, so the only way doing a `PyErr_Clear` on deletion could do
anything if is some *other* exception was raised while the
`error_already_set` object was alive--but in that case, clearing some
other exception seems wrong.  (Code that is worried about an exception
handler raising another exception would already catch a second
`error_already_set` from exception code).

The destructor itself called `clear()`, but `clear()` was a little bit
more paranoid that needed: it called `restore()` to restore the
currently captured error, but then immediately cleared it, using the
`PyErr_Restore` to release the references.  That's unnecessary: it's
valid for us to release the references manually.  This updates the code
to simply release the references on the three objects (preserving the
gil acquire).

`clear()`, however, also had the side effect of clearing the current
error, even if the current `error_already_set` didn't have a current
error (e.g. because of a previous `restore()` or `clear()` call).  I
don't really see how clearing the error here can ever actually be
useful: the only way the current error could be set is if you called
`restore()` (in which case the current stored error-related members have
already been released), or if some *other* code raised the error, in
which case `clear()` on *this* object is clearing an error for which it
shouldn't be responsible.

Neither of those seem like intentional or desirable features, and
manually requesting deletion of the stored references similarly seems
pointless, so I've just made `clear()` an empty method and marked it
deprecated.

This also fixes a minor potential issue with the destruction: it is
technically possible for `value` to be null (though this seems likely to
be rare in practice); this updates the check to look at `type` which
will always be non-null for a `Fetch`ed exception.

This also adds error_already_set round-trip throw tests to the test
suite.
2017-07-28 20:40:35 -04:00
Jason Rhinelander abcf43d59c Convert test_exceptions to new testing style 2017-07-28 20:40:35 -04:00
Jason Rhinelander 353615f77e Make `init_holder` do registration, and rename to `init_instance`
The instance registration for offset base types fails (under macOS, with
a segfault) in the presense of virtual base types.  The issue occurs
when trying to `static_cast<Base *>(derived_ptr)` when `derived_ptr` has
been allocated (via `operator new`) but not initialized.

This commit fixes the issue by moving the addition to
`registered_instances` into `init_holder` rather than immediately after
value pointer allocation.

This also renames it to `init_instance` since it does more than holder
initialization now.  (I also further renamed `init_holder_helper` to
`init_holder` since `init_holder` isn't used anymore).

Fixes #959.
2017-07-28 20:39:33 -04:00
Jason Rhinelander 44a17e1f3d Convert test_multiple_inheritance to new style
Significant rearrangement, but no new tests added.
2017-07-28 20:39:33 -04:00
Ivan Smirnov e07f75839d Implicit conversions to bool + np.bool_ conversion (#925)
This adds support for implicit conversions to bool from Python types
with `__bool__` (Python 3) or `__nonzero__` (Python 2) attributes, and
adds direct (i.e. non-converting) support for numpy bools.
2017-07-23 11:02:43 -04:00
Jason Rhinelander a03408c839 Add support custom sized operator deletes (#952)
If a class doesn't provide a `T::operator delete(void *)` but does have
a `T::operator delete(void *, size_t)` the latter is invoked by a
`delete someT`.  Pybind currently only look for and call the former;
this commit adds detection and calling of the latter when the former
doesn't exist.
2017-07-23 00:32:58 -04:00
Jason Rhinelander 60526d4636 Support `take_ownership` for custom type casters given a pointer
This changes the pointer `cast()` in `PYBIND11_TYPE_CASTER` to recognize
the `take_ownership` policy: if casting a pointer with take-ownership,
the `cast()` now recalls `cast()` with a dereferenced rvalue (rather
than the previous code, which was always calling it with a const lvalue
reference), and deletes the pointer after the chained `cast()` is
complete.

This makes code like:

    m.def("f", []() { return new std::vector<int>(100, 1); },
        py::return_value_policy::take_ownership);

do the expected thing by taking over ownership of the returned pointer
(which is deleted once the chained cast completes).
2017-07-16 11:04:43 -04:00
Jason Rhinelander 67a0cc4eed Fix regression: container pointers not castable
PR #936 broke the ability to return a pointer to a stl container (and,
likewise, to a tuple) because the added deduced type matched a
non-const pointer argument: the pointer-accepting `cast` in
PYBIND11_TYPE_CASTER had a `const type *`, which is a worse match for a
non-const pointer than the universal reference template #936 added.

This changes the provided TYPE_CASTER cast(ptr) to take the pointer by
template arg (so that it will accept either const or non-const pointer).
It has two other effects: it slightly reduces .so size (because many
type casters never actually need the pointer cast at all), and it allows
type casters to provide their untemplated pointer `cast()` that will
take precedence over the templated version provided in the macro.
2017-07-16 11:04:43 -04:00
Jason Rhinelander 6b51619a7c Fix test suite under MSVC/Debug
In a Debug build, MSVC doesn't apply copy/move elision as often,
triggering a test failure.  This relaxes the test count requirements
to let the test suite pass.
2017-07-12 11:50:40 -04:00
Jason Rhinelander b57281bb00 Use rvalue subcasting when casting an rvalue container
This updates the std::tuple, std::pair and `stl.h` type casters to
forward their contained value according to whether the container being
cast is an lvalue or rvalue reference.  This fixes an issue where
subcaster casts were always called with a const lvalue which meant
nested type casters didn't have the desired `cast()` overload invoked.
For example, this caused Eigen values in a tuple to end up with a
readonly flag (issue #935) and made it impossible to return a container
of move-only types (issue #853).

This fixes both issues by adding templated universal reference `cast()`
methods to the various container types that forward container elements
according to the container reference type.
2017-07-05 12:27:14 -04:00
Jason Rhinelander 897d71687e Combine std::tuple/std::pair logic
The std::pair caster can be written as a special case of the std::tuple
caster; this combines them via a base `tuple_caster` class (which is
essentially identical to the previous std::tuple caster).

This also removes the special empty tuple base case: returning an empty
tuple is relatively rare, and the base case still works perfectly well
even when the tuple types is an empty list.
2017-07-05 12:27:14 -04:00
Jason Rhinelander 23bf894590 Override deduced Base class when defining Derived methods
When defining method from a member function pointer (e.g. `.def("f",
&Derived::f)`) we run into a problem if `&Derived::f` is actually
implemented in some base class `Base` when `Base` isn't
pybind-registered.

This happens because the class type is deduced from the member function
pointer, which then becomes a lambda with first argument this deduced
type.  For a base class implementation, the deduced type is `Base`, not
`Derived`, and so we generate and registered an overload which takes a
`Base *` as first argument.  Trying to call this fails if `Base` isn't
registered (e.g.  because it's an implementation detail class that isn't
intended to be exposed to Python) because the type caster for an
unregistered type always fails.

This commit adds a `method_adaptor` function that rebinds a member
function to a derived type member function and otherwise (i.e. regular
functions/lambda) leaves the argument as-is.  This is now used for class
definitions so that they are bound with type being registered rather
than a potential base type.

A closely related fix in this commit is to similarly update the lambdas
used for `def_readwrite` (and related) to bind to the class type being
registered rather than the deduced type so that registering a property
that resolves to a base class member similarly generates a usable
function.

Fixes #854, #910.

Co-Authored-By: Dean Moldovan <dean0x7d@gmail.com>
2017-07-03 17:28:45 -04:00
Jason Rhinelander 259b2fafea Fix unsigned error value casting
When casting to an unsigned type from a python 2 `int`, we currently
cast using `(unsigned long long) PyLong_AsUnsignedLong(src.ptr())`.
If the Python cast fails, it returns (unsigned long) -1, but then we
cast this to `unsigned long long`, which means we get 4294967295, but
because that isn't equal to `(unsigned long long) -1`, we don't detect
the failure.

This commit moves the unsigned casting into a `detail::as_unsigned`
function which, upon error, casts -1 to the final type, and otherwise
casts the return value to the final type to avoid the problematic double
cast when an error occurs.

The error most commonly shows up wherever `long` is 32-bits (e.g. under
both 32- and 64-bit Windows, and under 32-bit linux) when passing a
negative value to a bound function taking an `unsigned long`.

Fixes #929.

The added tests also trigger a latent segfault under PyPy: when casting
to an integer smaller than `long` (e.g. casting to a `uint32_t` on a
64-bit `long` architecture) we check both for a Python error and also
that the resulting intermediate value will fit in the final type.  If
there is no conversion error, but we get a value that would overflow, we
end up calling `PyErr_ExceptionMatches()` illegally: that call is only
allowed when there is a current exception.  Under PyPy, this segfaults
the test suite.  It doesn't appear to segfault under CPython, but the
documentation suggests that it *could* do so.  The fix is to only check
for the exception match if we actually got an error.
2017-07-02 15:27:51 -04:00
Dean Moldovan 30f6c3b36e Fix indirect loading of Eigen::Ref
Put the caster's temporary array on life support to ensure correct
lifetime when it's being used as a subcaster.
2017-06-29 11:31:54 +02:00
Dean Moldovan af2dda38ef Add a life support system for type_caster temporaries 2017-06-29 11:31:54 +02:00
Andreas Bergmeier 34b7b54f29 Add tests for passing STL containers by pointer
`nullptr` is not expected to work in this case.
2017-06-27 10:38:41 +02:00
Dean Moldovan c67033a926 Move test_cmake_build target code into its subdirectory 2017-06-27 10:38:41 +02:00
Dean Moldovan 0bc272b2e9 Move tests from short translation units into their logical parents 2017-06-27 10:38:41 +02:00
Dean Moldovan 83e328f58c Split test_python_types.cpp into builtin_casters, stl and pytypes 2017-06-27 10:38:41 +02:00
Dean Moldovan bdfb50f384 Move tests from test_issues.cpp/py into appropriate files 2017-06-27 10:38:41 +02:00
Dean Moldovan cd2d3ad5df Fix embedded threads test on MSVC2015 / Python 2.7 2017-06-24 21:59:55 +02:00
Bruce Merry 9d698f7fcc Hold strong references to keep_alive patients
This fixes #856. Instead of the weakref trick, the internals structure
holds an unordered_map from PyObject* to a vector of references. To
avoid the cost of the unordered_map lookup for objects that don't have
any keep_alive patients, a flag is added to each instance to indicate
whether there is anything to do.
2017-06-24 12:59:46 -04:00
Dean Moldovan 2d6116b53f Fix GIL release and acquire when embedding the interpreter
Fixes a race condition when multiple threads try to acquire the GIL
before `detail::internals` have been initialized. `gil_scoped_release`
is now tasked with initializing `internals` (guaranteed single-threaded)
to ensure the safety of subsequent `acquire` calls from multiple threads.
2017-06-24 14:03:42 +02:00
Jason Rhinelander f42af24a7d Support std::string_view when compiled under C++17 2017-06-24 03:24:56 -03:00
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