On 01/21/2014 01:52 PM, Gary Oberbrunner wrote:
>
> ----- Original Message -----
>> From: "Stefan Seefeld" <ste...@seefeld.name>
> ...
>> It seems what you really want is a way for your C++ code to
>> manipulate pure Python objects, without any automatic type conversion.
> Yes!
>
>> So the cleanest way to do that would be to use the above definition of
>> the "Effect" class (in Python), import that into your C++ runtime
>> (via bpl::import()), and then instantiate an "Effect" object with your
>> pre-defined dict object.
> I'm trying to do this in a boost python extension, so it has to be all in 
> C++.  If I have to wrap some python around it, it'll become a bit too 
> heavyweight.  

Have a look at the attached code; I don't think that counts as
heavy-weight. In particular, trying to do the same without  embedding a
little "script" would be just more cumbersome, if it worked at all.


> I'd love to do what you suggest above, if it can be done all in C++.  I think 
> all I need is a way to create, in C++, an empty Python class object with a 
> __dict__.  Then, as you say, I can add attributes to it (at least I think I 
> should be able to - but I'm not sure how far the boost.python world goes).

Compile the attached as a stand-alone app. I think it demonstrates what
you want, so you should be able to easily adjust it to your use-case.

        Stefan


-- 

      ...ich hab' noch einen Koffer in Berlin...

#include <boost/python.hpp>
#include <string>

namespace bpl = boost::python;

char const *code = 
  "class Struct:                       \n"
  "    def __init__(self, attrs):      \n"
  "        self.__dict__.update(attrs) \n";

int main(int argc, char** argv)
{
  Py_Initialize();
  try
  {
    // set up a tiny Python session to define a "Struct" class.
    bpl::object main = bpl::import("__main__");
    bpl::object global(main.attr("__dict__"));
    bpl::object result = bpl::exec(code, global, global);
    bpl::object type = global["Struct"];
    // now instantiate it with a dictionary.
    bpl::dict attrs;
    attrs["number"] = 42;
    bpl::object o = type(attrs);
    // and show that it contains the expected attribute(s)
    std::cout << bpl::extract<char const *>(bpl::str(o.attr("number"))) << std::endl;
  }
  catch (bpl::error_already_set &)
  {
    PyErr_Print();
  }
}
_______________________________________________
Cplusplus-sig mailing list
Cplusplus-sig@python.org
https://mail.python.org/mailman/listinfo/cplusplus-sig

Reply via email to