user_na user_na -4 years ago 127
Python Question

How do I correctly access struct values and pass them to functions- boost::python

I am struggeling to build a c++ python wrapper using boost. This might be a very basic question, but I failed to see the answer in the various existing tutorials.

[update: The fist part about how to access the struct data members was solved by xioxox post. The question which is still open is:
How do I write the wrapper for the vector inside the struct.]

[original post]
My C++ Part looks something like this:

struct Globals {
AClass *a;
BClass *b;
int someInt = 5;
bool check = FALSE;
vector<unsigned short> someData
};

void func1(Globals* global)
{
// ...
// a propper inizialisation of the globals a and b Classes
// ...
global->check = global->a->returnSomething1(global->someInt);
if(global->check)
{
global->someData = global->b->returnSomething2();
}
return;
}

BOOST_PYTHON_MODULE(demo)
{
using namespace boost::python;
class_<Globals>("Globals")
.def_readonly("check", &Globals::check)
.def_readwrite("someint", &Globals::someint);
//someData to be done...

def("func1", func1);

}


With Python I want to create a
Globals
Object, set the
someInt
inside of it and then pass it to
func1
. After the funcion is done I want to read the
check
value and if it is true, also the results saved in
someData
via python again.

When I import the libary in an IPython console it will give the following result

In [1]: import demo as d

In [2]: T = d.Globals

In [3]: T
Out[3]: demo.Globals

In [4]: T.check
Out[4]: <property at 0xa2c72c8>

In [5]: T.someInt
Out[5]: <property at 0xa2c7278>

In [6]: T.someInt = 5

In [7]: d.func1(T)
Out[7]: <property at 0xa2c7278>

Traceback (most recent call last):

File "<ipython-input-7-dc39ba21a63e>", line 1, in <module>
demo.func1(T)

ArgumentError: Python argument types in demo.func1(Boost.Python.class)
did not match C++ signature:
func1(struct Globals * __ptr64)


When I try to access the values I only see the C++ pointers. The struct however is changed into a
Boost.Python.class
as far as I understand it, I would have to get a pointer from this class and pass this as the
Globals*
input. How do I do that?

I also want to access the Vector data (
sapGlobal->images.data()
) in python, but I have no idea how to implement the wrapper for it.

Any help with that would be highly appreciated.

[update 2] The vector can be wrapped by including
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

and adding the following line to the
BOOST_PYTHON_MODULE


class_<vector<unsigned short>>("img")
.def(vector_indexing_suite<vector<unsigned short>>());


As described here

Answer Source

The problem is that T is actually the class you have declared, and not an instance of the class. You need to say

T = d.Globals()

instead of

T = d.Globals
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download