Commit Graph

345 Commits

Author SHA1 Message Date
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
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
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
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
Jason Rhinelander
929009954b Expose more instance management functions
This breaks up the instance management functions in class_support.h a
little bit so that other pybind11 code can use it.  In particular:

- added make_new_instance() which does what pybind11_object_new does,
  but also allows instance allocation without `value` allocation.  This
  lets `cast.h` use the same instance allocation rather than having its
  own separate implementation.
- instance registration is now moved to a
  `register_instance()`/deregister_instance()` pair (rather than having
  individual code add or remove things from `registered_instances`
  directory).
- clear_instance() does everything `pybind11_object_dealloc()` needs
  except for the deallocation; this is helpful for factory construction
  which needs to be able to replace the internals of an instance without
  deallocating it.
- clear_instance() now also calls `dealloc` when `holder_constructed`
  is true, even if `value` is false.  This can happen in factory
  construction when the pointer is moved from one instance to another,
  but the holder itself is only copied (i.e. for a shared_ptr holder).
2017-04-27 09:12:41 -04:00
Jason Rhinelander
501135fa76 Add static_assert to holder casters
The holder casters assume but don't check that a `holder<type>`'s `type`
is really a `type_caster_base<type>`; this adds a static_assert to make
sure this is really the case, to turn things like
`std::shared_ptr<array>` into a compilation failure.

Fixes #785
2017-04-08 10:55:51 -04:00
Ivan Smirnov
7348c407f6 Fix -Wmissing-braces warning 2017-04-05 18:03:08 -04:00
Jason Rhinelander
6906b270d6 Improve make_tuple error message under debugging
When make_tuple fails (for example, when print() is called with a
non-convertible argument, as in #778) the error message a less helpful
than it could be:

    make_tuple(): unable to convert arguments of types 'std::tuple<type1, type2>' to Python object

There is no actual std::tuple involved (only a parameter pack and a
Python tuple), but it also doesn't immediately reveal which type caused
the problem.

This commit changes the debugging mode output to show just the
problematic type:

    make_tuple(): unable to convert argument of type 'type2' to Python object
2017-04-05 11:43:05 -04:00
Dean Moldovan
1ac19036d6 Add a scope guard call policy
```c++
m.def("foo", foo, py::call_guard<T>());
```

is equivalent to:

```c++
m.def("foo", [](args...) {
    T scope_guard;
    return foo(args...); // forwarded arguments
});
```
2017-04-03 00:52:47 +02:00
Dean Moldovan
0d765f4a7c Support class-specific operator new and delete
Fixes #754.
2017-03-22 19:28:04 +01:00
Dean Moldovan
cd3d1fc7df Throw an exception when attempting to load an incompatible holder
Instead of a segfault. Fixes #751.

This covers the case of loading a custom holder from a default-holder
instance. Attempting to load one custom holder from a different custom
holder (i.e. not `std::unique_ptr`) yields undefined behavior, just as
#588 established for inheritance.
2017-03-21 10:26:22 +01:00
Dean Moldovan
819cb5533e Fix nullptr to None conversion for builtin type casters
Fixes #731.

Generally, this applies to any caster made with PYBIND11_TYPE_CASTER().
2017-03-16 13:57:35 +01:00
Jason Rhinelander
ee9296395d Call PyUnicode_DecodeUTF* directly
Some versions of Python 2.7 reportedly (#713) have issues with
PyUnicode_Decode being passed the encoding string, so just skip it
entirely by calling the PyUnicode_DecodeUTF* function directly.  This
will also be slightly more efficient by avoiding having to check the
encoding string, and (for python 2) going through the unicode class's
decode (python 3 fast-tracks this for all utf-{8,16,32} encodings;
python 2 only fast-tracked for the exact string "utf-8", which we
weren't passing anyway (we had "utf8")).

This doesn't work for PyPy, however: its `PyUnicode_DecodeUTF{8,16,32}`
appear rather broken: the UTF8 one segfaults, while the 16/32 require
recasting into a non-const `char *` (and might segfault; I didn't get
far enough to find out).  Just avoid the whole thing by keeping the
encoding-passed-as-string version for PyPy, which seems to work
reliably.
2017-03-12 00:17:51 -04:00
eirrgang
11c9f32c0f fix python version check (#705)
Commit 11a337f1 added major and minor python version
checking to cast.h but does not use the macros defined
via the Python.h inclusion. This may be due to an
intention to use the variables defined by the cmake
module FindPythonInterpreter, but nothing in the
pybind11 repo does anything to convert the cmake
variables to preprocessor defines.
2017-03-01 10:53:38 +01:00
Jason Rhinelander
546f6fce1a Add an ability to avoid forcing rvp::move
Eigen::Ref objects, when returned, are almost always returned as
rvalues; what's important is the data they reference, not the outer
shell, and so we want to be able to use `::copy`,
`::reference_internal`, etc. to refer to the data the Eigen::Ref
references (in the following commits), rather than the Eigen::Ref
instance itself.

This moves the policy override into a struct so that code that wants to
avoid it (or wants to provide some other Return-type-conditional
override) can create a specialization of
return_value_policy_override<Return> in order to override the override.

This lets an Eigen::Ref-returning function be bound with `rvp::copy`,
for example, to specify that the data should be copied into a new numpy
array rather than referenced, or `rvp::reference_internal` to indicate
that it should be referenced, but a keep-alive used (actually, we used
the array's `base` rather than a py::keep_alive in such a case, but it
accomplishes the same thing).
2017-02-24 23:19:50 +01:00
Jason Rhinelander
ee2e5a5086 Make string conversion stricter (#695)
* Make string conversion stricter

The string conversion logic added in PR #624 for all std::basic_strings
was derived from the old std::wstring logic, but that was underused and
turns out to have had a bug in accepting almost anything convertible to
unicode, while the previous std::string logic was much stricter.  This
restores the previous std::string logic by only allowing actual unicode
or string types.

Fixes #685.

* Added missing 'requires numpy' decorator

(I forgot that the change to a global decorator here is in the
not-yet-merged Eigen PR)
2017-02-24 11:33:31 +01:00
Dean Moldovan
08cbe8dfed Make all classes with the same instance size derive from a common base
In order to fully satisfy Python's inheritance type layout requirements,
all types should have a common 'solid' base. A solid base is one which
has the same instance size as the derived type (not counting the space
required for the optional `dict_ptr` and `weakrefs_ptr`). Thus, `object`
does not qualify as a solid base for pybind11 types and this can lead to
issues with multiple inheritance.

To get around this, new base types are created: one per unique instance
size. There is going to be very few of these bases. They ensure Python's
MRO checks will pass when multiple bases are involved.
2017-02-23 15:45:26 +01:00
Dean Moldovan
c91f8bd627 Reimplement static properties by extending PyProperty_Type
Instead of creating a new unique metaclass for each type, the builtin
`property` type is subclassed to support static properties. The new
setter/getters always pass types instead of instances in their `self`
argument. A metaclass is still required to support this behavior, but
it doesn't store any data anymore, so a new one doesn't need to be
created for each class. There is now only one common metaclass which
is shared by all pybind11 types.
2017-02-23 15:45:26 +01:00
Jason Rhinelander
11a337f16f Unicode fixes and docs (#624)
* Propagate unicode conversion failure

If returning a std::string with invalid utf-8 data, we currently fail
with an uninformative TypeError instead of propagating the
UnicodeDecodeError that Python sets on failure.

* Add support for u16/u32strings and literals

This adds support for wchar{16,32}_t character literals and the
associated std::u{16,32}string types.  It also folds the
character/string conversion into a single type_caster template, since
the type casters for string and wstring were mostly the same anyway.

* Added too-long and too-big character conversion errors

With this commit, when casting to a single character, as opposed to a
C-style string, we make sure the input wasn't a multi-character string
or a single character with codepoint too large for the character type.

This also changes the character cast op to CharT instead of CharT& (we
need to be able to return a temporary decoded char value, but also
because there's little gained by bothering with an lvalue return here).

Finally it changes the char caster to 'has-a-string-caster' instead of
'is-a-string-caster' because, with the cast_op change above, there's
nothing at all gained from inheritance.  This also lets us remove the
`success` from the string caster (which was only there for the char
caster) into the char caster itself.  (I also renamed it to 'none' and
inverted its value to better reflect its purpose).  The None -> nullptr
loading also now takes place only under a `convert = true` load pass.
Although it's unlikely that a function taking a char also has overloads
that can take a None, it seems marginally more correct to treat it as a
conversion.

This commit simplifies the size assumptions about character sizes with
static_asserts to back them up.
2017-02-14 11:08:19 +01:00
Matthew Woehlke
e15fa9f99a Avoid C-style const casts (#659)
* Avoid C-style const casts

Replace C-style casts that discard `const` with `const_cast` (and, where
necessary, `reinterpret_cast` as well).

* Warn about C-style const-discarding casts

Change pybind11_enable_warnings to also enable `-Wcast-qual` (warn if a
C-style cast discards `const`) by default. The previous commit should
have gotten rid of all of these (at least, all the ones that tripped in
my build, which included the tests), and this should discourage more
from newly appearing.
2017-02-08 23:43:08 +01:00
Jason Rhinelander
abc29cad02 Add support for non-converting arguments
This adds support for controlling the `convert` flag of arguments
through the py::arg annotation.  This then allows arguments to be
flagged as non-converting, which the type_caster is able to use to
request different behaviour.

Currently, AFAICS `convert` is only used for type converters of regular
pybind11-registered types; all of the other core type_casters ignore it.
We can, however, repurpose it to control internal conversion of
converters like Eigen and `array`: most usefully to give callers a way
to disable the conversion that would otherwise occur when a
`Eigen::Ref<const Eigen::Matrix>` argument is passed a numpy array that
requires conversion (either because it has an incompatible stride or the
wrong dtype).

Specifying a noconvert looks like one of these:

    m.def("f1", &f, "a"_a.noconvert() = "default"); // Named, default, noconvert
    m.def("f2", &f, "a"_a.noconvert()); // Named, no default, no converting
    m.def("f3", &f, py::arg().noconvert()); // Unnamed, no default, no converting

(The last part--being able to declare a py::arg without a name--is new:
previous py::arg() only accepted named keyword arguments).

Such an non-convert argument is then passed `convert = false` by the
type caster when loading the argument.  Whether this has an effect is up
to the type caster itself, but as mentioned above, this would be
extremely helpful for the Eigen support to give a nicer way to specify
a "no-copy" mode than the custom wrapper in the current PR, and
moreover isn't an Eigen-specific hack.
2017-02-03 20:18:15 -05:00
Jason Rhinelander
709675a7aa Made arithmetic and complex casters respect convert
Arithmetic and complex casters now only do a converting cast when
`convert=true`; previously they would convert always (e.g. when passing
an int to a float-accepting function, or a float to complex-accepting
function).
2017-02-03 20:16:14 -05:00
Jason Rhinelander
bfcf952e01 Pack all function call data into a single struct
This cleans up the previous commit slightly by further reducing the
function call arguments to a single struct (containing the
function_record, arguments vector, and parent).

Although this doesn't currently change anything, it does allow for
future functionality to have a place for precalls to store temporary
objects that need to be destroyed after a function call (whether or not
the call succeeds).

As a concrete example, with this change #625 could be easily implemented
(I think) by adding a std::unique_ptr<gil_scoped_release> member to the
`function_call` struct with a precall that actually constructs it.
Without this, the precall can't do that: the postcall won't be invoked
if the call throws an exception.

This doesn't seems to affect the .so size noticeably (either way).
2017-01-31 17:24:41 +01:00
Jason Rhinelander
70ed2a4897 Use constexpr_first for args/kwargs positional checks 2017-01-31 17:24:41 +01:00
Jason Rhinelander
34d308adf0 Move constexpr_first/last to common.h
This keeps it with constexpr_sum and the other metafunctions.
2017-01-31 17:24:41 +01:00
Jason Rhinelander
2686da8350 Add support for positional args with args/kwargs
This commit rewrites the function dispatcher code to support mixing
regular arguments with py::args/py::kwargs arguments.  It also
simplifies the argument loader noticeably as it no longer has to worry
about args/kwargs: all of that is now sorted out in the dispatcher,
which now simply appends a tuple/dict if the function takes
py::args/py::kwargs, then passes all the arguments in a vector.

When the argument loader hit a py::args or py::kwargs, it doesn't do
anything special: it just calls the appropriate type_caster just like it
does for any other argument (thus removing the previous special cases
for args/kwargs).

Switching to passing arguments in a single std::vector instead of a pair
of tuples also makes things simpler, both in the dispatch and the
argument_loader: since this argument list is strictly pybind-internal
(i.e. it never goes to Python) we have no particular reason to use a
Python tuple here.

Some (intentional) restrictions:
- you may not bind a function that has args/kwargs somewhere other than
  the end (this somewhat matches Python, and keeps the dispatch code a
  little cleaner by being able to not worry about where to inject the
  args/kwargs in the argument list).
- If you specify an argument both positionally and via a keyword
  argument, you get a TypeError alerting you to this (as you do in
  Python).
2017-01-31 17:24:41 +01:00
Dean Moldovan
ec009a7ca2 Improve custom holder support (#607)
* Abstract away some holder functionality (resolve #585)

Custom holder types which don't have `.get()` can select the correct
function to call by specializing `holder_traits`.

* Add support for move-only holders (fix #605)
2017-01-31 17:05:44 +01:00
Jason Rhinelander
f7f5bc8e37 Numpy: better compilation errors, long double support (#619)
* Clarify PYBIND11_NUMPY_DTYPE documentation

The current documentation and example reads as though
PYBIND11_NUMPY_DTYPE is a declarative macro along the same lines as
PYBIND11_DECLARE_HOLDER_TYPE, but it isn't.  The changes the
documentation and docs example to make it clear that you need to "call"
the macro.

* Add satisfies_{all,any,none}_of<T, Preds>

`satisfies_all_of<T, Pred1, Pred2, Pred3>` is a nice legibility-enhanced
shortcut for `is_all<Pred1<T>, Pred2<T>, Pred3<T>>`.

* Give better error message for non-POD dtype attempts

If you try to use a non-POD data type, you get difficult-to-interpret
compilation errors (about ::name() not being a member of an internal
pybind11 struct, among others), for which isn't at all obvious what the
problem is.

This adds a static_assert for such cases.

It also changes the base case from an empty struct to the is_pod_struct
case by no longer using `enable_if<is_pod_struct>` but instead using a
static_assert: thus specializations avoid the base class, POD types
work, and non-POD types (and unimplemented POD types like std::array)
get a more informative static_assert failure.

* Prefix macros with PYBIND11_

numpy.h uses unprefixed macros, which seems undesirable.  This prefixes
them with PYBIND11_ to match all the other macros in numpy.h (and
elsewhere).

* Add long double support

This adds long double and std::complex<long double> support for numpy
arrays.

This allows some simplification of the code used to generate format
descriptors; the new code uses fewer macros, instead putting the code as
different templated options; the template conditions end up simpler with
this because we are now supporting all basic C++ arithmetic types (and
so can use is_arithmetic instead of is_integral + multiple
different specializations).

In addition to testing that it is indeed working in the test script, it
also adds various offset and size calculations there, which
fixes the test failures under x86 compilations.
2017-01-31 17:00:15 +01:00
Dean Moldovan
57a9bbc6c7 Automate generation of reference docs with doxygen and breathe (#598)
* Make 'any' the default markup role for Sphinx docs

* Automate generation of reference docs with doxygen and breathe

* Improve reference docs coverage
2017-01-31 16:54:08 +01:00
Pim Schellart
cc88aaecc8 Add check for matching holder_type when inheriting (#588) 2017-01-31 16:52:11 +01:00
Dean Moldovan
5f07facef5 Fix pointer to reference error in type_caster on MSVC (#583) 2017-01-03 11:52:05 +01:00
Wenzel Jakob
1d1f81b278 WIP: PyPy support (#527)
This commit includes modifications that are needed to get pybind11 to work with PyPy. The full test suite compiles and runs except for a last few functions that are commented out (due to problems in PyPy that were reported on the PyPy bugtracker).

Two somewhat intrusive changes were needed to make it possible: two new tags ``py::buffer_protocol()`` and ``py::metaclass()`` must now be specified to the ``class_`` constructor if the class uses the buffer protocol and/or requires a metaclass (e.g. for static properties).

Note that this is only for the PyPy version based on Python 2.7 for now. When the PyPy 3.x has caught up in terms of cpyext compliance, a PyPy 3.x patch will follow.
2016-12-16 15:00:46 +01:00
Lori A. Burns
c79e435e00 remove constexpr to help export void arg functions with Intel (#557) 2016-12-16 00:15:24 +01:00
Wenzel Jakob
2029171211 always_construct_holder feature to support intrusively reference-counted types (#561)
* always_construct_holder feature to support intrusively reference-counted types

* added testcase
2016-12-15 23:44:23 +01:00
Jason Rhinelander
fa5d05e15d Change all_of_t/any_of_t to all_of/any_of, add none_of
This replaces the current `all_of_t<Pred, Ts...>` with `all_of<Ts...>`,
with previous use of `all_of_t<Pred, Ts...>` becoming
`all_of<Pred<Ts>...>` (and similarly for `any_of_t`).  It also adds a
`none_of<Ts...>`, a shortcut for `negation<any_of<Ts...>>`.

This allows `all_of` and `any_of` to be used a bit more flexible, e.g.
in cases where several predicates need to be tested for the same type
instead of the same predicate for multiple types.

This commit replaces the implementation with a more efficient version
for non-MSVC.  For MSVC, this changes the workaround to use the
built-in, recursive std::conjunction/std::disjunction instead.

This also removes the `count_t` since `any_of_t` and `all_of_t` were the
only things using it.

This commit also rearranges some of the future std imports to use actual
`std` implementations for C++14/17 features when under the appropriate
compiler mode, as we were already doing for a few things (like
index_sequence).  Most of these aren't saving much (the implementation
for enable_if_t, for example, is trivial), but I think it makes the
intention of the code instantly clear.  It also enables MSVC's native
std::index_sequence support.
2016-12-14 20:42:36 +01:00
Jason Rhinelander
b11b144603 Remove duplicate protected:/private: 2016-12-14 20:40:49 +01:00
Jason Rhinelander
12ce07a2c2 Remove useless convert argument from argument_loader
Since the argument loader split off from the tuple converter, it is
never called with a `convert` argument set to anything but true.  This
removes the argument entirely, passing a literal `true` from within
`argument_loader` to the individual value casters.
2016-12-14 20:40:49 +01:00
Jason Rhinelander
23e59c8633 Work around gcc 7 ICE
Current g++ 7 snapshot fails to compile pybind under -std=c++17 with:

```
$ make
[  3%] Building CXX object tests/CMakeFiles/pybind11_tests.dir/pybind11_tests.cpp.o
In file included from /home/jagerman/src/pybind11/tests/pybind11_tests.h:2:0,
                 from /home/jagerman/src/pybind11/tests/pybind11_tests.cpp:10:
/home/jagerman/src/pybind11/include/pybind11/pybind11.h: In instantiation of 'pybind11::cpp_function::initialize(Func&&, Return (*)(Args ...), const Extra& ...)::<lambda(pybind11::detail::function_record*, pybind11::handle, pybind11::handle, pybind11::handle)> [with Func = pybind11::cpp_function::cpp_function(Return (Class::*)(Arg ...), const Extra& ...) [with Return = int; Class = ConstructorStats; Arg = {}; Extra = {pybind11::name, pybind11::is_method, pybind11::sibling}]::<lambda(ConstructorStats*)>; Return = int; Args = {ConstructorStats*}; Extra = {pybind11::name, pybind11::is_method, pybind11::sibling}]':
/home/jagerman/src/pybind11/include/pybind11/pybind11.h:120:22:   required from 'struct pybind11::cpp_function::initialize(Func&&, Return (*)(Args ...), const Extra& ...) [with Func = pybind11::cpp_function::cpp_function(Return (Class::*)(Arg ...), const Extra& ...) [with Return = int; Class = ConstructorStats; Arg = {}; Extra = {pybind11::name, pybind11::is_method, pybind11::sibling}]::<lambda(ConstructorStats*)>; Return = int; Args = {ConstructorStats*}; Extra = {pybind11::name, pybind11::is_method, pybind11::sibling}]::<lambda(struct pybind11::detail::function_record*, class pybind11::handle, class pybind11::handle, class pybind11::handle)>'
/home/jagerman/src/pybind11/include/pybind11/pybind11.h:120:19:   required from 'void pybind11::cpp_function::initialize(Func&&, Return (*)(Args ...), const Extra& ...) [with Func = pybind11::cpp_function::cpp_function(Return (Class::*)(Arg ...), const Extra& ...) [with Return = int; Class = ConstructorStats; Arg = {}; Extra = {pybind11::name, pybind11::is_method, pybind11::sibling}]::<lambda(ConstructorStats*)>; Return = int; Args = {ConstructorStats*}; Extra = {pybind11::name, pybind11::is_method, pybind11::sibling}]'
/home/jagerman/src/pybind11/include/pybind11/pybind11.h:62:9:   required from 'pybind11::cpp_function::cpp_function(Return (Class::*)(Arg ...), const Extra& ...) [with Return = int; Class = ConstructorStats; Arg = {}; Extra = {pybind11::name, pybind11::is_method, pybind11::sibling}]'
/home/jagerman/src/pybind11/include/pybind11/pybind11.h:984:22:   required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = int (ConstructorStats::*)(); Extra = {}; type_ = ConstructorStats; options = {}]'
/home/jagerman/src/pybind11/tests/pybind11_tests.cpp:24:47:   required from here
/home/jagerman/src/pybind11/include/pybind11/pybind11.h:147:9: sorry, unimplemented: unexpected AST of kind cleanup_stmt
         };
         ^
/home/jagerman/src/pybind11/include/pybind11/pybind11.h:147:9: internal compiler error: in potential_constant_expression_1, at cp/constexpr.c:5593
0x84c52a potential_constant_expression_1
	../../src/gcc/cp/constexpr.c:5593
0x84c3c0 potential_constant_expression_1
	../../src/gcc/cp/constexpr.c:5154
0x645511 finish_function(int)
	../../src/gcc/cp/decl.c:15527
0x66e80b instantiate_decl(tree_node*, int, bool)
	../../src/gcc/cp/pt.c:22558
0x6b61e2 instantiate_class_template_1
	../../src/gcc/cp/pt.c:10444
0x6b61e2 instantiate_class_template(tree_node*)
	../../src/gcc/cp/pt.c:10514
0x75a676 complete_type(tree_node*)
	../../src/gcc/cp/typeck.c:133
0x67d5a4 tsubst_copy_and_build(tree_node*, tree_node*, int, tree_node*, bool, bool)
	../../src/gcc/cp/pt.c:17516
0x67ca19 tsubst_copy_and_build(tree_node*, tree_node*, int, tree_node*, bool, bool)
	../../src/gcc/cp/pt.c:16655
0x672cce tsubst_expr(tree_node*, tree_node*, int, tree_node*, bool)
	../../src/gcc/cp/pt.c:16140
0x6713dc tsubst_expr(tree_node*, tree_node*, int, tree_node*, bool)
	../../src/gcc/cp/pt.c:15408
0x671915 tsubst_expr(tree_node*, tree_node*, int, tree_node*, bool)
	../../src/gcc/cp/pt.c:15394
0x671fc0 tsubst_expr(tree_node*, tree_node*, int, tree_node*, bool)
	../../src/gcc/cp/pt.c:15618
0x66e97f tsubst_expr(tree_node*, tree_node*, int, tree_node*, bool)
	../../src/gcc/cp/pt.c:15379
0x66e97f instantiate_decl(tree_node*, int, bool)
	../../src/gcc/cp/pt.c:22536
0x6ba0cb instantiate_pending_templates(int)
	../../src/gcc/cp/pt.c:22653
0x6fd7f8 c_parse_final_cleanups()
	../../src/gcc/cp/decl2.c:4512
```

which looks a lot like https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77545.

The error seems to be that it gets confused about the `std::tuple<...>
value` in argument_loader: it is apparently not being initialized
properly.  Adding a default constructor with an explicit
default-initialization of `value` works around the problem.
2016-12-14 20:40:49 +01:00
Jason Rhinelander
3f1ff3f4d1 Adds automatic casting on assignment of non-pyobject types (#551)
This adds automatic casting when assigning to python types like dict,
list, and attributes.  Instead of:

    dict["key"] = py::cast(val);
    m.attr("foo") = py::cast(true);
    list.append(py::cast(42));

you can now simply write:

    dict["key"] = val;
    m.attr("foo") = true;
    list.append(42);

Casts needing extra parameters (e.g. for a non-default rvp) still
require the py::cast() call. set::add() is also supported.

All usage is channeled through a SFINAE implementation which either just returns or casts. 

Combined non-converting handle and autocasting template methods via a
helper method that either just returns (handle) or casts (C++ type).
2016-12-12 23:42:52 +01:00
Dean Moldovan
ab90ec6ce9 Allow references to objects held by smart pointers (#533) 2016-12-07 02:36:44 +01:00
Dean Moldovan
8c85a85747 Use C++14 index_sequence when possible
Newer standard libraries use compiler intrinsics for std::index_sequence
which makes it ‘free’. This prevents hitting instantiation limits for
recursive templates (-ftemplate-depth).
2016-12-03 23:13:53 +01:00
Dean Moldovan
107285b353 Accept any sequence type as std::tuple or std::pair
This is more Pythonic and compliments the std::vector and std::list
casters which also accept sequences.
2016-12-03 23:13:53 +01:00
Dean Moldovan
719c1733dd Split up tuple caster and function argument loader
This is needed in order to allow the tuple caster to accept any sequence
while keeping the argument loader fast. There is also very little overlap
between the two classes which makes the separation clean. It’s also good
practice not to have completely new functionality in a specialization.
2016-12-03 23:13:53 +01:00
Jason Rhinelander
14bfe622f8 Simplify cast_op return type (#532)
Using a complicated declval here was pointlessly complicated: we
already know the type, because that's what cast_op_type<T> is in the
first place.  (The declval also broke MSVC).
2016-11-25 19:23:01 +01:00
Jason Rhinelander
db86f7f285 Clean up cast operator invocations (#531)
This adds a `detail::cast_op<T>(caster)` function which handles the
rather verbose:

    caster.operator typename CasterType::template cast_op_type<T>()

which allows various places to use the shorter and clearer:

    cast_op<T>(caster)

instead of the full verbose cast operator invocation.
2016-11-25 18:35:00 +01:00
Wenzel Jakob
e72d958a5d detail::error_string: handle call stacks that switch between C++ and Python multiple times 2016-11-24 12:48:31 +01:00
Dean Moldovan
d079f41c26 Always use return_value_policy::move for rvalues (#510)
Fixes #509.

The move policy was already set for rvalues in PR #473, but this only
applied to directly cast user-defined types. The problem is that STL
containers cast values indirectly and the rvalue information is lost.
Therefore the move policy was not set correctly. This commit fixes it.

This also makes an additional adjustment to remove the `copy` policy
exception: rvalues now always use the `move` policy. This is also safe
for copy-only rvalues because the `move` policy has an internal fallback
to copying.
2016-11-20 05:31:02 +01:00
Dean Moldovan
c7ac16bb2e Add py::reinterpret_borrow<T>()/steal<T>() for low-level unchecked casts
The pytype converting constructors are convenient and safe for user
code, but for library internals the additional type checks and possible
conversions are sometimes not desired. `reinterpret_borrow<T>()` and
`reinterpret_steal<T>()` serve as the low-level unsafe counterparts
of `cast<T>()`.

This deprecates the `object(handle, bool)` constructor.

Renamed `borrowed` parameter to `is_borrowed` to avoid shadowing
warnings on MSVC.
2016-11-17 08:55:42 +01:00
Dean Moldovan
e18bc02fc9 Add default and converting constructors for all concrete Python types
* Deprecate the `py::object::str()` member function since `py::str(obj)`
  is now equivalent and preferred

* Make `py::repr()` a free function

* Make sure obj.cast<T>() works as expected when T is a Python type

`obj.cast<T>()` should be the same as `T(obj)`, i.e. it should convert
the given object to a different Python type. However, `obj.cast<T>()`
usually calls `type_caster::load()` which only checks the type without
doing any actual conversion. That causes a very unexpected `cast_error`.
This commit makes it so that `obj.cast<T>()` and `T(obj)` are the same
when T is a Python type.

* Simplify pytypes converting constructor implementation

It's not necessary to maintain a full set of converting constructors
and assignment operators + const& and &&. A single converting const&
constructor will work and there is no impact on binary size. On the
other hand, the conversion functions can be significantly simplified.
2016-11-17 08:55:42 +01:00
Dean Moldovan
b4498ef44d Add py::isinstance<T>(obj) for generalized Python type checking
Allows checking the Python types before creating an object instead of
after. For example:
```c++
auto l = list(ptr, true);
if (l.check())
   // ...
```
The above is replaced with:
```c++
if (isinstance<list>(ptr)) {
    auto l = reinterpret_borrow(ptr);
    // ...
}
```

This deprecates `py::object::check()`. `py::isinstance()` covers the
same use case, but it can also check for user-defined types:
```c++
class Pet { ... };
py::class_<Pet>(...);

m.def("is_pet", [](py::object obj) {
    return py::isinstance<Pet>(obj); // works as expected
});
```
2016-11-17 08:55:42 +01:00
Ivan Smirnov
425b4970b2 Add type casters for nullopt_t, fix none refcount (#499)
* Incref returned None in std::optional type caster

* Add type casters for nullopt_t

* Add a test for nullopt_t
2016-11-15 13:00:38 +01:00
Jason Rhinelander
617fbcfc1e Fix stl_bind to support movable, non-copyable value types (#490)
This commit includes the following changes:

* Don't provide make_copy_constructor for non-copyable container

make_copy_constructor currently fails for various stl containers (e.g.
std::vector, std::unordered_map, std::deque, etc.) when the container's
value type (e.g. the "T" or the std::pair<K,T> for a map) is
non-copyable.  This adds an override that, for types that look like
containers, also requires that the value_type be copyable.

* stl_bind.h: make bind_{vector,map} work for non-copy-constructible types

Most stl_bind modifiers require copying, so if the type isn't copy
constructible, we provide a read-only interface instead.

In practice, this means that if the type is non-copyable, it will be,
for all intents and purposes, read-only from the Python side (but
currently it simply fails to compile with such a container).

It is still possible for the caller to provide an interface manually
(by defining methods on the returned class_ object), but this isn't
something stl_bind can handle because the C++ code to construct values
is going to be highly dependent on the container value_type.

* stl_bind: copy only for arithmetic value types

For non-primitive types, we may well be copying some complex type, when
returning by reference is more appropriate.  This commit returns by
internal reference for all but basic arithmetic types.

* Return by reference whenever possible

Only if we definitely can't--i.e. std::vector<bool>--because v[i]
returns something that isn't a T& do we copy; for everything else, we
return by reference.

For the map case, we can always return by reference (at least for the
default stl map/unordered_map).
2016-11-15 12:30:38 +01:00
Wenzel Jakob
5e1c0445cf include backtrace in pybind11::detail::error_string (#494) 2016-11-12 16:57:30 +09:00
Wenzel Jakob
fe40dfe67d address number caster regression (fixes #484) 2016-11-07 15:59:01 +01:00
Dean Moldovan
03f627ebb1 Make reference(_internal) the default return value policy for properties (#473)
* Make reference(_internal) the default return value policy for properties

Before this, all `def_property*` functions used `automatic` as their
default return value policy. This commit makes it so that:

 * Non-static properties use `reference_interal` by default, thus
   matching `def_readonly` and `def_readwrite`.

 * Static properties use `reference` by default, thus matching
   `def_readonly_static` and `def_readwrite_static`.

In case `cpp_function` is passed to any `def_property*`, its policy will
be used instead of any defaults. User-defined arguments in `extras`
still have top priority and will override both the default policies and
the ones from `cpp_function`.

Resolves #436.

* Almost always use return_value_policy::move for rvalues

For functions which return rvalues or rvalue references, the only viable
return value policies are `copy` and `move`. `reference(_internal)` and
`take_ownership` would take the address of a temporary which is always
an error.

This commit prevents possible user errors by overriding the bad rvalue
policies with `move`. Besides `move`, only `copy` is allowed, and only
if it's explicitly selected by the user.

This is also a necessary safety feature to support the new default
return value policies for properties: `reference(_internal)`.
2016-11-01 11:44:57 +01:00
Wenzel Jakob
496feacfd0 pybind11: implicitly convert NumPy integer scalars
The current integer caster was unnecessarily strict and rejected
various kinds of NumPy integer types when calling C++ functions
expecting normal integers. This relaxes the current behavior.
2016-10-28 01:02:46 +02:00
Wenzel Jakob
dd9bd7778f Merge pull request #453 from aldanor/feature/numpy-scalars
NumPy scalars to ctypes conversion support
2016-10-25 01:15:25 +02:00
Ivan Smirnov
8f3e045deb Use detail::get_type_info() wherever sensible
This reduces direct access to internals.registered_types_cpp to
just a few places.
2016-10-24 23:55:52 +01:00
Ivan Smirnov
a6e6a8b108 Require existing typeinfo for direct conversions
This avoid a hashmap lookup since the pointer to the list of
direct converters is now cached in the typeinfo.
2016-10-23 15:29:10 +01:00
Wenzel Jakob
c0d19192d2 minor indentation change 2016-10-22 13:08:44 -04:00
Ben North
24a2054dbc Fix wrapper's 'value' and 'owned' if ctor missing
type_caster_generic::cast(): The values of

    wrapper->value
    wrapper->owned

are incorrect in the case that a return value policy of 'copy' is
requested but there is no copy-constructor.  (Similarly 'move'.)  In
particular, if the source object is a static instance, the destructor of
the 'object' 'inst' leads to class_::dealloc() which incorrectly
attempts to 'delete' the static instance.

This commit re-arranges the code to be clearer as to what the values of
'value' and 'owned' should be in the various cases.  Behaviour is
different to previous code only in two situations:

policy = copy but no copy-ctor: Old code leaves 'value = src, owned =
true', which leads to trouble.  New code leaves 'value = nullptr, owned
= false', which is correct.

policy = move but no move- or copy-ctor: old code leaves 'value = src,
owned = true', which leads to trouble.  New code leaves 'value =
nullptr, owned = false', which is correct.
2016-10-20 21:32:55 +01:00
Ivan Smirnov
ccc69f91f4 Cache direct converters in the generic type caster 2016-10-20 16:52:24 +01:00
Ivan Smirnov
85e16262d6 Enable direct conversions with no typeinfo present 2016-10-20 16:46:40 +01:00
Ivan Smirnov
c275ee6b46 Add support for "direct" converters 2016-10-20 16:09:31 +01:00
Dean Moldovan
5d28dd1194 Support std::shared_ptr holder type out of the box
With this there is no more need for manual user declarations like
`PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)`. Existing ones
will still compile without error -- they will just be ignored silently.

Resolves #446.
2016-10-20 16:19:58 +02:00
Jason Rhinelander
12d76600f8 Disable most implicit conversion constructors
We have various classes that have non-explicit constructors that accept
a single argument, which is implicitly making them implicitly
convertible from the argument.  In a few cases, this is desirable (e.g.
implicit conversion of std::string to py::str, or conversion of double
to py::float_); in many others, however, it is unintended (e.g. implicit
conversion of size_t to some pre-declared py::array_t<T> type).

This disables most of the unwanted implicit conversions by marking them
`explicit`, and comments the ones that are deliberately left implicit.
2016-10-16 16:27:42 -04:00
Wenzel Jakob
e71ab8f455 unpacking_collector: allow nullptr-valued kwargs argument
This fixes an issue that can arise when forwarding (*args, **kwargs)
captured from a pybind11-bound function call to another Python function.
When the initial function call includes no keyword arguments, the
py::kwargs field is set to nullptr and causes a crash later on.
2016-10-08 15:30:02 +02:00
Wenzel Jakob
103d78d368 failed implicit conversions shouldn't lead to nullptr dereference 2016-09-30 13:43:19 +02:00
Wenzel Jakob
cd4d7d6bf8 very minor caster simplification 2016-09-30 12:20:19 +02:00
Dean Moldovan
242b146a51 Extend attribute and item accessor interface using object_api 2016-09-23 02:00:01 +02:00
Dean Moldovan
865e43034b Make attr and item accessors throw on error instead of returning nullptr
This also adds the `hasattr` and `getattr` functions which are needed
with the new attribute behavior. The new functions behave exactly like
their Python counterparts.

Similarly `object` gets a `contains` method which calls `__contains__`,
i.e. it's the same as the `in` keyword in Python.
2016-09-23 01:40:22 +02:00
Dean Moldovan
37e22e436e Move common object functions into object_api mixin 2016-09-23 01:38:35 +02:00
Wenzel Jakob
c1fc27e2b5 use detail::enable_if_t everywhere 2016-09-19 13:45:34 +02:00
Wenzel Jakob
8e5dceb6a6 Multiple inheritance support 2016-09-19 13:45:31 +02:00
Jason Rhinelander
4a4fb396e7 Fix build under debug mode
Take load_type by nested type_caster template arguments instead of by
full type_caster type.
2016-09-12 16:21:40 -04:00
Wenzel Jakob
f22683806e Merge pull request #400 from jagerman/add-ref-virtual-macros
Add a way to deal with copied value references
2016-09-12 06:32:39 +09:00
Jason Rhinelander
3e4fe6c0a8 Store a static type_caster rather than the basic type 2016-09-11 12:17:41 -04:00
Jason Rhinelander
f3f53e2b03 Removed unused/unwanted public ref_cast 2016-09-11 11:36:33 -04:00
Jason Rhinelander
7dfb932e70 Update OVERLOAD macros to support ref/ptr return type overloads
This adds a static local variable (in dead code unless actually needed)
in the overload code that is used for storage if the overload is for
some convert-by-value type (such as numeric values or std::string).

This has limitations (as written up in the advanced doc), but is better
than simply not being able to overload reference or pointer methods.
2016-09-11 01:21:53 -04:00
Dean Moldovan
f69071ca4b Make it easier to add new binding of builtin Python exceptions 2016-09-10 16:14:36 +02:00
Dean Moldovan
135ba8deaf Make error_already_set fetch and hold the Python error
This clears the Python error at the error_already_set throw site, thus
allowing Python calls to be made in destructors which are triggered by
the exception. This is preferable to the alternative, which would be
guarding every Python API call with an error_scope.

This effectively flips the behavior of error_already_set. Previously,
it was assumed that the error stays in Python, so handling the exception
in C++ would require explicitly calling PyErr_Clear(), but nothing was
needed to propagate the error to Python. With this change, handling the
error in C++ does not require a PyErr_Clear() call, but propagating the
error to Python requires an explicit error_already_set::restore().

The change does not break old code which explicitly calls PyErr_Clear()
for cleanup, which should be the majority of user code. The need for an
explicit restore() call does break old code, but this should be mostly
confined to the library and not user code.
2016-09-10 12:08:32 +02:00
Wenzel Jakob
720136bfa7 RAII wrapper for error state 2016-09-10 16:32:17 +09:00
Wenzel Jakob
9d7f7a38a7 fixed Py_None reference couting 2016-09-08 22:53:18 +09:00
Wenzel Jakob
5812d64ba2 Merge pull request #394 from jagerman/fix-ref-heap-casts
Fix ref heap casts
2016-09-08 09:05:15 +09:00
Wenzel Jakob
587aa328c6 Merge pull request #395 from aldanor/feature/error-already-set-message
error_already_set improvements
2016-09-08 09:03:41 +09:00
Ivan Smirnov
984c762485 Use handle::is_none() instead of raw ptrs 2016-09-07 21:16:26 +01:00
Ivan Smirnov
67b54894b2 Set error if it's not set in error_already_set() 2016-09-07 21:10:16 +01:00
Jason Rhinelander
c03db9bad9 Fail static_assert when trying to reference non-referencable types
The previous commit to address #392 triggers a compiler warning about
returning a reference to a local variable, which is *not* a false alarm:
the following:

    py::cast<int &>(o)

(which happens internally in an overload declaration) really is
returning a reference to a local, because the cast operators for the
type_caster for numeric types returns a reference to its own member.

This commit adds a static_assert to make that a compilation failure
rather than returning a reference into about-to-be-freed memory.

Incidentally, this is also a fix for #219, which is exactly the same
issue: we can't reference numeric primitives that are cast from
wrappers around python numeric types.
2016-09-07 16:07:59 -04:00
Ivan Smirnov
392f16ccb8 Properly format type name in error_already_set() 2016-09-07 20:36:28 +01:00
Jason Rhinelander
56f717756b Fix type caster for heap reference types
Need to use the intrinsic type, not the raw type.

Fixes #392.
2016-09-07 14:14:11 -04:00
Wenzel Jakob
6fd3132e81 Merge pull request #385 from jagerman/relax-class-arguments
Allow arbitrary class_ template option ordering
2016-09-07 23:49:00 +09:00
Jason Rhinelander
6b52c838d7 Allow passing base types as a template parameter
This allows a slightly cleaner base type specification of:

    py::class_<Type, Base>("Type")

as an alternative to

    py::class_<Type>("Type", py::base<Base>())

As with the other template parameters, the order relative to the holder
or trampoline types doesn't matter.

This also includes a compile-time assertion failure if attempting to
specify more than one base class (but is easily extendible to support
multiple inheritance, someday, by updating the class_selector::set_bases
function to set multiple bases).
2016-09-06 20:34:24 -04:00
Jason Rhinelander
5fffe200e3 Allow arbitrary class_ template option ordering
The current pybind11::class_<Type, Holder, Trampoline> fixed template
ordering results in a requirement to repeat the Holder with its default
value (std::unique_ptr<Type>) argument, which is a little bit annoying:
it needs to be specified not because we want to override the default,
but rather because we need to specify the third argument.

This commit removes this limitation by making the class_ template take
the type name plus a parameter pack of options.  It then extracts the
first valid holder type and the first subclass type for holder_type and
trampoline type_alias, respectively.  (If unfound, both fall back to
their current defaults, `std::unique_ptr<type>` and `type`,
respectively).  If any unmatched template arguments are provided, a
static assertion fails.

What this means is that you can specify or omit the arguments in any
order:

    py::class_<A, PyA> c1(m, "A");
    py::class_<B, PyB, std::shared_ptr<B>> c2(m, "B");
    py::class_<C, std::shared_ptr<C>, PyB> c3(m, "C");

It also allows future class attributes (such as base types in the next
commit) to be passed as class template types rather than needing to use
a py::base<> wrapper.
2016-09-06 12:22:13 -04:00
Wenzel Jakob
c84b37b577 fix bogus return value policy fallbacks (fixes #389) 2016-09-07 00:47:17 +09:00
Dean Moldovan
60b26802fd Make keyword argument hold a py::object instead of T*
With this change arg_t is no longer a template, but it must remain so
for backward compatibility. Thus, a non-template arg_v is introduced,
while a dummy template alias arg_t is there to keep old code from
breaking. This can be remove in the next major release.

The implementation of arg_v also needed to be placed a little earlier in
the headers because it's not a template any more and unpacking_collector
needs more than a forward declaration.
2016-09-06 16:41:50 +02:00
Dean Moldovan
8fe13b8896 Apply make_caster and intrinsic_t aliases everywhere 2016-09-06 16:41:50 +02:00
Dean Moldovan
56e86ed094 Workaround for py::dict() constructor on MSVC
MSVC fails to compile if the constructor is defined out-of-line.
The error states that it cannot deduce the type of the default template
parameter which is used for SFINAE.
2016-09-06 16:41:50 +02:00
Dean Moldovan
16db1bfbd7 Remove superseded handle::operator() overloads
The variadic handle::operator() offers the same functionality as well
as mixed positional, keyword, * and ** arguments. The tests are also
superseded by the ones in `test_callbacks`.
2016-09-06 16:41:50 +02:00
Dean Moldovan
15a112f8ff Add py::dict() keyword constructor 2016-09-06 16:41:50 +02:00
Dean Moldovan
c743e1b1b4 Support keyword arguments and generalized unpacking in C++
A Python function can be called with the syntax:
```python
foo(a1, a2, *args, ka=1, kb=2, **kwargs)
```
This commit adds support for the equivalent syntax in C++:
```c++
foo(a1, a2, *args, "ka"_a=1, "kb"_a=2, **kwargs)
```

In addition, generalized unpacking is implemented, as per PEP 448,
which allows calls with multiple * and ** unpacking:
```python
bar(*args1, 99, *args2, 101, **kwargs1, kz=200, **kwargs2)
```
and
```c++
bar(*args1, 99, *args2, 101, **kwargs1, "kz"_a=200, **kwargs2)
```
2016-09-06 16:41:50 +02:00
Wenzel Jakob
fe34241e50 minor doc & style fixes 2016-09-06 13:02:29 +09:00
Jason Rhinelander
a6495af87a Make unique_ptr's with non-default deleters work
Currently pybind11 only supports std::unique_ptr<T> holders by default
(other holders can, of course, be declared using the macro).  PR #368
added a `py::nodelete` that is intended to be used as:

    py::class_<Type, std::unique_ptr<Type, py::nodelete>> c("Type");

but this doesn't work out of the box.  (You could add an explicit
holder type declaration, but this doesn't appear to have been the
intention of the commit).

This commit fixes it by generalizing the unique_ptr type_caster to take
both the type and deleter as template arguments, so that *any*
unique_ptr instances are now automatically handled by pybind.  It also
adds a test to test_smart_ptr, testing both that py::nodelete (now)
works, and that the object is indeed not deleted as intended.
2016-09-04 18:23:55 -04:00
Jason Rhinelander
5aa85be26e Added pybind11::make_key_iterator for map iteration
This allows exposing a dict-like interface to python code, allowing
iteration over keys via:

    for k in custommapping:
        ...

while still allowing iteration over pairs, so that you can also
implement 'dict.items()' functionality which returns a pair iterator,
allowing:

    for k, v in custommapping.items():
        ...

example-sequences-and-iterators is updated with a custom class providing
both types of iteration.
2016-08-11 21:22:05 -04:00
Jason Rhinelander
e20fc61a33 Silence MSVC warning
PR #329 generates the following warning under MSVC:

    ...\cast.h(202): warning C4456: declaration of 'it' hides previous local declaration

This renames the second iterator to silence it.
2016-08-11 16:23:23 -04:00
Jason Rhinelander
f2ecd8927e Implement reference_internal with a keep_alive
reference_internal requires an `instance` field to track the returned
reference's parent, but that's just a duplication of what
keep_alive<0,1> does, so use a keep alive to do this to eliminate the
duplication.
2016-08-10 12:08:04 -04:00
Jason Rhinelander
1b05ce5bc0 Track registered instances that share a pointer address
The pointer to the first member of a class instance is the same as the
pointer to instance itself; pybind11 has some workarounds for this to
not track registered instances that have a registered parent with the
same address.  This doesn't work everywhere, however: issue #328 is a
failure of this for a mutator operator which resolves its argument to
the parent rather than the child, as is needed in #328.

This commit resolves the issue (and restores tracking of same-address
instances) by changing registered_instances from an unordered_map to an
unordered_multimap that allows duplicate instances for the same pointer
to be recorded, then resolves these differences by checking the type of
each matched instance when looking up an instance.  (A
unordered_multimap seems cleaner for this than a unordered_map<list> or
similar because, the vast majority of the time, the instance will be
unique).
2016-08-09 17:57:59 -04:00
Jason Rhinelander
ed14879a19 Move support for return values of called Python functions
Currently pybind11 always translates values returned by Python functions
invoked from C++ code by copying, even when moving is feasible--and,
more importantly, even when moving is required.

The first, and relatively minor, concern is that moving may be
considerably more efficient for some types.  The second problem,
however, is more serious: there's currently no way python code can
return a non-copyable type to C++ code.

I ran into this while trying to add a PYBIND11_OVERLOAD of a virtual
method that returns just such a type: it simply fails to compile because
this:

    overload = ...
    overload(args).template cast<ret_type>();

involves a copy: overload(args) returns an object instance, and the
invoked object::cast() loads the returned value, then returns a copy of
the loaded value.

We can, however, safely move that returned value *if* the object has the
only reference to it (i.e. if ref_count() == 1) and the object is
itself temporary (i.e. if it's an rvalue).

This commit does that by adding an rvalue-qualified object::cast()
method that allows the returned value to be move-constructed out of the
stored instance when feasible.

This basically comes down to three cases:

- For objects that are movable but not copyable, we always try the move,
  with a runtime exception raised if this would involve moving a value
  with multiple references.
- When the type is both movable and non-trivially copyable, the move
  happens only if the invoked object has a ref_count of 1, otherwise the
  object is copied.  (Trivially copyable types are excluded from this
  case because they are typically just collections of primitive types,
  which can be copied just as easily as they can be moved.)
- Non-movable and trivially copy constructible objects are simply
  copied.

This also adds examples to example-virtual-functions that shows both a
non-copyable object and a movable/copyable object in action: the former
raises an exception if returned while holding a reference, the latter
invokes a move constructor if unreferenced, or a copy constructor if
referenced.

Basically this allows code such as:

    class MyClass(Pybind11Class):
        def somemethod(self, whatever):
            mt = MovableType(whatever)
            # ...
            return mt

which allows the MovableType instance to be returned to the C++ code
via its move constructor.

Of course if you attempt to violate this by doing something like:

    self.value = MovableType(whatever)
    return self.value

you get an exception--but right now, the pybind11-side of that code
won't compile at all.
2016-08-08 13:47:37 -04:00
Dean Moldovan
ed23dda93b Adopt PEP 484 type hints for C++ types exported to Python 2016-08-04 23:47:07 +02:00
Wenzel Jakob
6969e7c1ba exception handler tweaks (fixes #284) 2016-07-18 10:46:41 +02:00
Pim Schellart
5a7d17ff16 Add support for user defined exception translators 2016-07-11 17:33:04 -04:00
Jason Rhinelander
8469f751cb Add _<bool>("s1", "s2") ternary & use TYPE_CASTER
This commit adds an additional _ template function for compile-time
selection between two description strings.  This in turn allows the
elimination of needing two name() methods in type_caster<arithmetic
types> and type_caster<eigen types>, which allows them to start using
PYBIND11_TYPE_CASTER instead, simplifying their code by eliminating all
the code that they are duplicating from the macro.
2016-07-06 00:40:54 -04:00
Merlin Nimier-David
68ca3b6343 more informative error message when py::make_tuple fails 2016-07-01 20:35:35 +02:00
Wenzel Jakob
0006259508 switched internal usage of cast_error exception to reference_cast_error 2016-07-01 16:07:35 +02:00
Wenzel Jakob
472ffbba96 more informative error message when py::cast fails 2016-07-01 16:07:24 +02:00
Wenzel Jakob
37e1f61f54 allow passing a 'return value policy' to handle::operator() 2016-06-22 14:29:13 +02:00
Wenzel Jakob
0a07805ab6 fixed many conversion warnings on clang 2016-05-29 13:40:40 +02:00
Wenzel Jakob
69e1a5c91b quenched warnings on windows, comments in gil_scoped_release 2016-05-26 14:29:31 +02:00
Wenzel Jakob
3f200fab22 don't implicitly convert doubles to ints 2016-05-17 15:35:29 +02:00
Wenzel Jakob
178c8a899d nicer type_caster::load() calling conventions 2016-05-15 20:23:27 +02:00
Wenzel Jakob
6c03beb867 enable *args and **kwargs notation (closes #190) 2016-05-08 14:34:09 +02:00
Wenzel Jakob
ad69634907 minor cleanups 2016-05-03 13:36:32 +02:00
Wenzel Jakob
aadc2f3d8c cast(): use cast_op_type mechanism 2016-05-03 13:27:57 +02:00
Wenzel Jakob
bd57eb484d don't try to cast 'None' into a C++ lvalue reference 2016-05-01 14:42:20 +02:00
Wenzel Jakob
2bc946bd7a copy/move constructor detection workaround (MSVC 2015 bug) 2016-05-01 10:28:00 +02:00
Wenzel Jakob
8edfa0c10f further simplifications to shared_ptr caster 2016-04-30 23:01:06 +02:00
Wenzel Jakob
ffd85b46d8 return value policy fix for functions returning std::shared_ptr<> (fixes #187) 2016-04-30 22:41:05 +02:00
Wenzel Jakob
772c6d54d6 enable passing C++ instances to void*-valued arguments 2016-04-30 21:28:45 +02:00
Wenzel Jakob
e8b9dd263c fixed docstring generation for void pointers 2016-04-30 19:35:24 +02:00
Wenzel Jakob
fd7cf51a56 enabled casting of const void* 2016-04-30 19:25:37 +02:00
Wenzel Jakob
06f56ee1e9 opaque type redesign 2016-04-28 17:49:46 +02:00
Wenzel Jakob
f7b5874ca3 new move value policy 2016-04-25 23:04:27 +02:00
Wenzel Jakob
fbafdea672 a few more GIL-related compatibility fixes 2016-04-25 17:48:56 +02:00
Wenzel Jakob
39e97e6a49 significant redesign of GIL state handling 2016-04-25 03:27:32 +02:00
Wenzel Jakob
dbe43ffcce completed implicit type casters for reference_wrapper 2016-04-21 12:21:14 +02:00
Wenzel Jakob
f54ded74f1 added caster for std::reference_wrapper (fixes #171) 2016-04-20 17:00:57 +02:00
Wenzel Jakob
e65e58716e slight generalization of cast_op_type 2016-04-18 21:22:22 +02:00
Wenzel Jakob
8cb6cb33ef minor cleanups in common.h; updated author info and copyright year 2016-04-18 10:53:38 +02:00
Wenzel Jakob
1dc940d4b7 quenched -pendantic warnings (closes #167) 2016-04-18 10:41:44 +02:00
Wenzel Jakob
8bd31c71e4 New automatic return value policy for cat() and make_tuple(), fixed an ambiguity issue 2016-04-14 15:00:30 +02:00
Wenzel Jakob
d7efa4ff7b return best representation of polymorphic types (fixes #105) 2016-04-13 13:51:33 +02:00
Wenzel Jakob
505466ff0e added variadic make_tuple() function 2016-04-13 02:49:03 +02:00
Wenzel Jakob
9f0dfce84b returning unique pointers is now allowed 2016-04-06 17:38:18 +02:00
Wenzel Jakob
a3ee1a4591 improved pair type caster (fixes #155) 2016-04-06 11:51:00 +02:00
Wenzel Jakob
b90e68de7e another corner case (fixes #151) 2016-03-27 00:19:32 +01:00
Wenzel Jakob
08927e9809 tabs->spaces 2016-03-26 23:38:46 +01:00
Wenzel Jakob
9883ec01d7 allow nullptr string values (closes #138) 2016-03-26 23:37:51 +01:00
Wenzel Jakob
d3349af48b modularized logic in preceding change, fixed issue with char (fixes #150) 2016-03-26 23:04:10 +01:00
Wenzel Jakob
0772967ecf allow nullptr when passing void* values 2016-03-26 20:41:28 +01:00
Wenzel Jakob
de1bca864e added feature to pass void* pointers by popular demand 2016-03-26 17:51:09 +01:00
Wenzel Jakob
12cf543804 address compilation issue in MSVC 2016-03-26 17:29:33 +01:00
Wenzel Jakob
048373c1b4 explicitly route type casting operations to desired casting operator (fixes #147) 2016-03-26 17:21:19 +01:00
Wenzel Jakob
eda978e003 support for opaque types 2016-03-15 15:07:55 +01:00
Wenzel Jakob
17cdb06c1b fix severe regression involving character arrays (fixes #137) 2016-03-10 13:24:10 +01:00
Wenzel Jakob
81dfd2c51f Working type casters for wide strings and wide characters 2016-03-08 20:48:07 +01:00
Wenzel Jakob
309a85ba59 support std::shared_ptr<const X> and types that indirectly derive from std::enable_shared_from_this 2016-03-08 17:59:10 +01:00
Wenzel Jakob
77586fd6a2 add version suffix to internal pybind11 data structures to avoid conflicts with future versions 2016-03-06 13:50:26 +01:00
Wenzel Jakob
bce8a4b95c force explicit cast (fixes #130) 2016-03-06 13:30:23 +01:00
Wenzel Jakob
52f4c3aef3 handle nullptr arguments with custom holder types (fixes #124) 2016-03-03 14:05:06 +01:00
hulucc
a88334f9c2 add wchar_t caster 2016-03-02 15:07:08 +08:00
hulucc
c8f68b3d92 add wstring caster 2016-03-02 13:59:39 +08:00
Wenzel Jakob
4a50fa5cd4 Address issue with handle::cast<bool>(), quench warning in example 12 (fixes #110) 2016-02-23 23:51:01 +01:00
Wenzel Jakob
a3861b54c4 type_caster_generic::load(): accept Py_None as input 2016-02-23 13:37:14 +01:00
Ben Pritchard
0b6cff3d1d Fixes for compilation/segfault problems with Intel (issue 94) 2016-02-18 12:38:27 -05:00
Wenzel Jakob
b6cf75d66a address issue with std::type_info across module boundaries (fixes #86) 2016-01-29 11:39:32 +01:00
Wenzel Jakob
260bc58f57 improved SFINAE in type_caster_generic (closes #70) 2016-01-18 22:15:20 +01:00
Wenzel Jakob
48548ea4a5 general cleanup of the codebase
- new pybind11::base<> attribute to indicate a subclass relationship
- unified infrastructure for parsing variadic arguments in class_ and cpp_function
- use 'handle' and 'object' more consistently everywhere
2016-01-17 22:31:15 +01:00
Wenzel Jakob
d561cb010c fully moved __pybind11__ Python attributes to the C++ side, cleanup & documentation pass over the main header file 2016-01-17 22:31:15 +01:00
Wenzel Jakob
b2c2c79240 improved handling of shared/smart pointers
Previously, pybind11 required classes using std::shared_ptr<> to derive
from std::enable_shared_from_this<> (or compilation failures would ensue).

Everything now also works for classes that don't do this, assuming that
some basic rules are followed (e.g. never passing "raw" pointers of
instances manged by shared pointers). The safer
std::enable_shared_from_this<> approach continues to be supported.
2016-01-17 22:31:15 +01:00
Wenzel Jakob
4177ed4336 renamed decay -> intrinsic_type (fixes #59) 2016-01-17 22:31:15 +01:00
Wenzel Jakob
82ffd40870 type of void fixed (None -> NoneType) 2016-01-17 22:31:15 +01:00
Wenzel Jakob
56e9f4942b improved signature names for subclasses of pybind11::handle 2016-01-17 22:31:15 +01:00
Wenzel Jakob
d0325bbd97 switched a few admissible cases from PyTuple_Set/GetItem -> PyTuple_SET/GET_ITEM 2016-01-17 22:31:15 +01:00
Wenzel Jakob
27e8e1066b added new type pybind11::bytes, cleanup of various macros (fixes #49) 2016-01-17 22:31:15 +01:00
Wenzel Jakob
66c9a40213 Much more efficient generation of function signatures, updated docs
This modification taps into some newer C++14 features (if present) to
generate function signatures considerably more efficiently at compile
time rather than at run time.

With this change, pybind11 binaries are now *2.1 times* smaller compared
to the Boost.Python baseline in the benchmark. Compilation times get a
nice improvement as well.

Visual Studio 2015 unfortunately doesn't implement 'constexpr' well
enough yet to support this change and uses a runtime fallback.
2016-01-17 22:31:15 +01:00
Wenzel Jakob
2ac5044a05 moved processing of cpp_function arguments out of dispatch code
The cpp_function class accepts a variadic argument, which was formerly
processed twice -- once at registration time, and once in the dispatch
lambda function. This is not only unnecessarily slow but also leads to
code bloat since it adds to the object code generated for every bound
function. This change removes the second pass at dispatch time.

One noteworthy change of this commit is that default arguments are now
constructed (and converted to Python objects) right at declaration time.
Consider the following example:

py::class_<MyClass>("MyClass")
    .def("myFunction", py::arg("arg") = SomeType(123));

In this case, the change means that pybind11 must already be set up to
deal with values of the type 'SomeType', or an exception will be thrown.
Another change is that the "preview" of the default argument in the
function signature is generated using the __repr__ special method. If
it is not available in this type, the signature may not be very helpful,
i.e.:

|  myFunction(...)
|      Signature : (MyClass, arg : SomeType = <SomeType object at 0x101b7b080>) -> None

One workaround (other than defining SomeType.__repr__) is to specify the
human-readable preview of the default argument manually using the more
cumbersome arg_t notation:

py::class_<MyClass>("MyClass")
    .def("myFunction", py::arg_t<SomeType>("arg", SomeType(123), "SomeType(123)"));
2016-01-17 22:31:15 +01:00
Wenzel Jakob
f08a3f0622 Merge pull request #52 from tmiasko/const-correctness
Make handle and related classes const correct.
2016-01-10 21:34:55 +01:00
Tomasz Miąsko
ca77130be8 Use object class to hold partially converted python objects.
Using object class to hold converted object automatically deallocates
object if an exception is thrown or scope is left before constructing
complete Python object.

Additionally added method object::release() that allows to release
ownership of python object without decreasing its reference count.
2016-01-02 21:07:18 +01:00
Tomasz Miąsko
5d53ac4cbf Clean the type name alone, not the whole message. 2015-12-28 08:49:17 +01:00
Tomasz Miąsko
875df5528d Make handle and related classes const correct.
This gives handle classes a typical pointer semantics with respects to
constness.
2015-12-28 08:11:16 +01:00
Tomasz Miąsko
cc39b2f37f Add const modifier to handle::cast. 2015-12-26 19:01:28 +01:00
Wenzel Jakob
d1a24823bc considerable simplifications to the Python type casters 2015-12-16 12:17:46 +01:00
Wenzel Jakob
9b0b40e0b0 add converter for nullptr_t 2015-12-16 11:41:53 +01:00
Wenzel Jakob
62127a27b0 don't allow 'void' or 'void*' as a function argument 2015-12-13 13:09:42 +01:00
Wenzel Jakob
60c36db1c9 generic integer type handling 2015-11-30 12:45:34 +01:00
Wenzel Jakob
7f8d1c20f1 improved int_ constructor 2015-11-29 13:48:16 +01:00
Wenzel Jakob
6e213c9ca0 improved shared pointer support (fixes #14) 2015-11-24 23:18:32 +01:00
Wenzel Jakob
333e889ef2 Improved STL support, support for std::set 2015-11-14 19:04:49 +01:00
Wenzel Jakob
723bc65b27 fix for std::shared_ptr proposed by Vayu (fixes #8) 2015-11-12 23:27:20 +01:00
Wenzel Jakob
fa1bfb2ec7 do a fallback search over types to handle incompatible std::type_info* across module boundaries (fixes issue #4) 2015-10-22 16:04:53 +02:00
Wenzel Jakob
ad7bc01d51 fix build on linux 2015-10-20 01:11:17 +02:00
Wenzel Jakob
0fb8528edf factored out some common functionality to a non-templated parent class 2015-10-19 23:53:22 +02:00
Wenzel Jakob
b1b714023a consistent macro naming throughout the project 2015-10-18 16:48:30 +02:00
Wenzel Jakob
8f4eb00690 last breaking change: be consistent about the project name 2015-10-15 18:23:56 +02:00