The cxPython library provides support for interoperation between C++ and Python.
Python is a widely used dynamic programming language. It is a high level language, often its syntax allows for fewer lines of code than possible in languages such as C++ or Java. It features automatic memory management and has a large and comprehensive standard library.
The reflection of C++ entities provides the basis for accessing the C++ entities from Python.
Xcpp allows for reflection of the following:
These reflected things are organised into a hierarchy of C++ namespaces.
Python bindings are described for the following:
The following example declares a simple reflected C++ struct with a reflected member variable. Note that the global function CreateX() returns an X by value.
// C++ code
namespace ns
{
$struct+ X
{
$void Set(int v) { a = v; }
$int32 a;
};
$function+ X CreateX()
{
return X();
}
}
The reflected C++ struct is wrapped in a python object allowing for read and write access to its reflected member variables and the ability to call its reflected member functions. For example:
# python code
x = ns.CreateX()
x.a = 100
x.Set(200)
print 'x.a = ' + `x.a`
A python object can represent a pointer or reference to a heap allocated C++ object. Consider the following C++ code:
// C++ code
namespace ns
{
$function+ string8* CreateString()
{
return new string8;
}
$function+ void DeleteString(string8* s)
{
delete s;
}
$function+ void SetString(string8& s)
{
s = "hello world";
}
$function+ void WriteString(const string8& s)
{
std::cout << s;
}
}
These functions can be called directly from Python:
# python code
s = ns.CreateString()
ns.SetString(s)
ns.WriteString(s)
ns.DeleteString(s)
Note that although in C++ functions there is a distinction to be made between references and pointers, this is immaterial to the Python bindings.
It is possible to directly invoke a constructor of a reflected C++ type in Python. This returns a python object which owns a heap allocated C++ object of that type. The C++ object is automatically deleted when the python object is destroyed.
The python object which represents a reference to a heap allocated C++ object can be passed into functions that are passed that type by pointer, reference or value.
Consider the following C++ code
// C++ code
namespace ns
{
// Example of function with in-out parameter
$function+ void AddWorld(ceda::string8& x)
{
x += ",world";
}
}
# python code
# Allocates a string on the heap. x is like a pointer to a string
x = ceda.string8("initial value")
print 'x = ' + `x` # prints the address of the string
print 'x.val = ' + `x.val`
# Read/write the value of the string
x.val = "hello"
print 'x.val = ' + `x.val`
# x can be passed to functions that take a string by value, pointer or reference
ns.AddWorld(x)
print 'x.val = ' + `x.val`
which produces the following output:
x = 0x000002D406D44030
x.val = 'initial value'
x.val = 'hello'
x.val = 'hello,world'
cxPython └── cxPython.h