Salome HOME
4f8ab1fa49246c25400989a8667ff1545d8fb44b
[tools/py2cpp.git] / README
1 The py2cpp library was created in order to make easier the call of a python 
2 function within c++ sources. It provides convertion functions to and from a
3 python object for some basic c++ types (int, double, std:: string and 
4 collections for these types: std::vector, std::list, std::map). It is possible 
5 to add your own convertion functions for your own types.
6
7 Example of use
8 ---------------
9
10 Consider you have the following python file "mymodule.py":
11
12 ________________________________________________________________________________
13 def myfunction(a, b):
14   return "The result is", a/b
15 ________________________________________________________________________________
16   
17 You can call this function from c++ this way:
18
19 ________________________________________________________________________________
20   #include "TypeConversions.hxx"
21   #include "Result.hxx"
22   #include "PyFunction.hxx"
23   ...
24   Py_Initialize();
25   ...
26   std::string s;
27   double d;
28   py2cpp::PyFunction fn;
29   fn.load("mymodule", "myfunction");
30   py2cpp::pyResult(s,d) = fn(1,2);
31   ...
32   std::cout << "String parameter from the python function:" << s << std::endl;
33   std::cout << "Double parameter from the python function:" << d << std::endl;
34   ...
35   Py_Finalize();
36 ________________________________________________________________________________
37
38 The full example which also deals with possible errors, can be this:
39
40 ________________________________________________________________________________
41   #include "TypeConversions.hxx"
42   #include "Result.hxx"
43   #include "PyFunction.hxx"
44
45   #include <iostream>
46
47   int main()
48   {
49     Py_Initialize();
50     {
51     std::string s;
52     double d;
53     py2cpp::PyFunction fn;
54     fn.load("mymodule", "myfunction");
55     if(!fn)
56     {
57       std::cerr << "Impossible to load myfunction from the module mymodule!";
58       std::cerr << std::endl;
59       std::cerr << py2cpp::getLastPyError();
60     }
61     else
62     {
63       try
64       {
65         py2cpp::pyResult(s,d) = fn(1, 2);
66         std::cout << "String parameter from the python function:" << s << std::endl;
67         std::cout << "Double parameter from the python function:" << d << std::endl;
68       }
69       catch(const py2cpp::Exception& err)
70       {
71         std::cerr << err.what();
72       }
73     }
74     }
75     Py_Finalize();
76     return 0;
77   }
78 ________________________________________________________________________________