Skip to content

Instantly share code, notes, and snippets.

@tomthorogood
Created March 21, 2012 17:36
Show Gist options
  • Select an option

  • Save tomthorogood/2149971 to your computer and use it in GitHub Desktop.

Select an option

Save tomthorogood/2149971 to your computer and use it in GitHub Desktop.
Instantiating and calling Python classes from using Boost.Python within C++
// I had the worst time in the world trying to determine how to do this.
// I did not find the answer in one concise resource. I figured I'd make this available
// to anyone else having the same trouble.
#include <usr/include/boost/python.hpp> // use your path here
#include <iostream>
#include <string>
namespace py = boost::python;
int main()
{
Py_Initialize();
py::object
mRedis, // the Redis module
iRedis, // the Redis instance
vRedis, // the redis return value;
std::string cString; // to hold our string that we extract from redis...
// The following two lines are the equivalent of:
// import redis
// iRedis = redis.Redis()
mRedis = py::import("redis");
iRedis = mRedis.attr("Redis")();
// Then, we're ready to roll! Let's set and get values with redis:
iRedis.attr("set")("my.namespace.key", "Hello, Redis & C++ & Python!");
vRedis = iRedis.attr("get")("my.namespace.key");
cString = py::extract<std::string>(vRedis);
std::cout << cString << std::endl; //displays "Hello, Redis & C++ & Python!");
return 0;
}
@tomthorogood
Copy link
Copy Markdown
Author

The reason why I chose the Redis interface is because the c++ redis interface is underutilized, under documented, and not updated.The original problem I was trying to solve was to do explicitly this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment