0

I've read the tutorials on how to extend python with my own module with my own functions:

http://docs.python.org/release/3.1.3/extending/embedding.html#embedding-python-in-c

But how do I extend python so that my module contains a class which I can use in python? A class I have programmed in C++.

I've tried using boost::python earlier but bjam hangs on me when I try to build on mac os x. I'd like to keep things simple as my requirement is very simple:

I have three functions in my module which I call initialise(), run() and close().

At the moment I do this in python:

import mymodule
mymodule.initialise()
mymodule.run()
mymodule.run() # run again
mymodule.close()

I'd like to have a class with initialise() as the constructor, run() as my method, and close() as my destructor. I can then do this:

import mymodule
with mymodule.MyClass as my_class:
    my_class.run()
    my_class.run()

Here's some of my code at the moment:

static PyMethodDef MyModuleMethods[] = 
{
    {"initialise",  mymodule_initialise, METH_VARARGS, ""},
    {"run",  mymodule_run, METH_VARARGS, ""},
    {"close",  mymodule_close, METH_VARARGS, ""},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

Thanks,

Barry

1
  • If the class is something you wrote yourself, you could import from it implicitly in the files as necessary. Commented Mar 21, 2012 at 20:58

2 Answers 2

1

Take a look at https://stackoverflow.com/questions/1492755/python-c-binding-library-comparison for a comparison of the various tools that will assist you in interfacing C++ with Python especially if you are producing bindings for an entire library of C++ code.

Also, see http://wiki.python.org/moin/IntegratingPythonWithOtherLanguages for a similar list of information directly from Python.org

Edit:

That was a pretty substantial change to your question :) The with statement requires implementing __enter__ and __exit__ as your entry and exit points. Did you try using those method names in your C++ class? See http://effbot.org/zone/python-with-statement.htm and http://www.python.org/dev/peps/pep-0343/ for more info on the with statement.

Sign up to request clarification or add additional context in comments.

1 Comment

I haven't got that far yet, I will begin by calling close() explicitly once I can create my object. Then I'll worry about with.
0

I finally found this: http://docs.python.org/extending/newtypes.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.