Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Passing by value #161

Closed
JendaPlhak opened this issue Apr 12, 2016 · 7 comments
Closed

Passing by value #161

JendaPlhak opened this issue Apr 12, 2016 · 7 comments

Comments

@JendaPlhak
Copy link

Assume we have following c++ code -

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


struct Foo {
    std::string a;
};

void show(Foo f) {
    std::cout << f.a << std::endl;
}

namespace py = pybind11;

PYBIND11_PLUGIN(example) {
    py::module m("example", "pybind11 example plugin");

    m.def("show", &show, "Prints a");
    py::class_<Foo>(m, "Foo")
    .def_readwrite("a",    &Foo::a);

    return m.ptr();
}

And very simple python script where we create Bird structure and want to pass it by value to function show -

import sys
sys.path.append(".")
import example

b = example.Foo
b.a = "Hello"
example.show(b)

This, to me quite surprisingly, causes following error:

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    example.show(f)
TypeError: Incompatible function arguments. The following argument types are supported:
    1. (Foo) -> NoneType

Why is that so? Am I doing it wrong or passing by value is just not possible? I didn't really found anything about this in the docs :-/

@JendaPlhak
Copy link
Author

It would be quite alright if I were to pass the argument by reference, but I was unable to accomplish that either.

@wjakob
Copy link
Member

wjakob commented Apr 12, 2016

Huh? There is nothing called Bird in your example code. Do you mean Foo? Aren't you missing the parentheses, as in Foo()?

@wjakob wjakob closed this as completed Apr 12, 2016
@JendaPlhak
Copy link
Author

Sorry, already edited. I don't think that it is a problem of parenthesis. Python is quite happy about

f = example.Foo
f.a = "arfaf"
print(f.a)```

So I suppose the object f as such is fine.

@wjakob
Copy link
Member

wjakob commented Apr 12, 2016

Please just try with parentheses...

@JendaPlhak
Copy link
Author

You mean to do - f = example.Foo() ? That doesn't work since I didn't provide constructor for structure Foo. Is that the problem?

@wjakob
Copy link
Member

wjakob commented Apr 12, 2016

exactly.. please look at the documentation examples before posting here -- my resources for these kinds of support tickets are very limited.

@JendaPlhak
Copy link
Author

I see. Ok, sorry to bother, I will try harder next time.

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

No branches or pull requests

2 participants