Looking for example of embedded Python
Phil Austin
phil at geog.ubc.ca
Sat Apr 29 12:33:04 EDT 2000
chris_barker at my-deja.com writes:
> Hi,
>
> I'm trying to persuade my co-workers that it would be extememly usefull
> to imbed Python in some of our apps. I'm looking for example
> applications wioth Python embedded. Ideally something fairly small with
> source code available.
>
In addition to Demo/embed/demo.c, a nice example that tests Numpy
array classes using CXX-4.2 (http://CXX.sourceforge.net) has been
written by Paul Dubois. It works for me using KCC under solaris and
linux, and should also compile with g++ 2.95.2. (I got segfaults
under linux until I remember that the correct linker sequence
needed -Xlinker -export-dynamic, e.g:
gcc -Xlinker -export-dynamic demo.o -L/home/phil/lib/pythonmain/linux/lib/python1.5/config \
-lpython1.5 -lieee -ldl -lm -o mydemo
Here's the output, followed by the source:
<peacock ~/CXX/CXX-4.2> arraytest
Array facility test
[ 0. 0.5 1. 1.5 2. 2.5 3. 3.5 4. 4.5 5. 5.5]
Rank is 1
Species is 7
dimension(1) = 12
Pointers 125188, 1200b8, 125188
A list: [9.0, 4.0, 1.0]
toArray: [ 9. 4. 1.]
<type 'array'>
list+list: [ 18. 8. 2.]
add 2: [ 11. 6. 3.]
list[1]: 4.0
sorted: [ 1. 4. 9.]
/* Minimal main program -- everything is loaded from the library */
#include "Python.h"
#include <iostream>
#include "CXX_Array.h"
#include <algorithm>
using namespace Py;
extern "C" int Py_Main(int argc, char** argv);
extern "C" void Py_Initialize();
extern "C" void Py_Finalize();
//extern "C" void PyImport_ImportModule(char *name);
int
main(int argc, char** argv)
{
PyObject *ptype;
PyObject *pvalue;
PyObject *ptrace;
std::cout << "Array facility test" << std::endl;
Py_Initialize();
import_array();
PyImport_ImportModule("Numeric");
try {
Array t(12);
for(int i=0; i < t.length(); ++i) t[i] = Float(i / 2.0);
std::cout << t << std::endl;
std::cout << "Rank is " << t.rank() << std::endl;
std::cout << "Species is " << t.species() << std::endl;
std::cout << "dimension(1) = " << t.dimension(1) << std::endl;
std::cout << "Pointers " << t.ptr() << ", " << (void *) t.to_C() <<
", " << t.as_contiguous().ptr() << std::endl;
List w(3);
w[0] = Float(9.0);
w[1] = Float(4.0);
w[2] = Float(1.0);
Array from_list = toArray(w);
std::cout << "A list: " << w << std::endl;
std::cout << "toArray: " << from_list << std::endl;
std::cout << from_list.type() << std::endl;
//return Py_Main(argc, argv);
std::cout << "list+list: " << from_list + from_list << std::endl;
std::cout << "add 2: " << from_list + Int(2) << std::endl;
std::cout << "list[1]: " << from_list[1] << std::endl;
std::sort(from_list.begin(), from_list.end());
std::cout << "sorted: " << from_list << std::endl;
}
catch(Exception&) {
std::cout << "Test failed via Exception" << std::endl;
PyErr_Fetch (&ptype, &pvalue, &ptrace);
FromAPI p(pvalue);
Object v(p);
std::cout << v << std::endl;
}
Py_Finalize();
return 0;
}
More information about the Python-list
mailing list