]> SALOME platform Git repositories - tools/py2cpp.git/blob - README
Salome HOME
Export cmake configuration.
[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     std::string s;
51     double d;
52     py2cpp::PyFunction fn;
53     fn.load("mymodule", "myfunction");
54     if(!fn)
55     {
56       std::cerr << "Impossible to load myfunction from the module mymodule!";
57       std::cerr << std::endl;
58       std::cerr << py2cpp::getLastPyError();
59     }
60     else
61     {
62       try
63       {
64         py2cpp::pyResult(s,d) = fn(1, 2);
65         std::cout << "String parameter from the python function:" << s << std::endl;
66         std::cout << "Double parameter from the python function:" << d << std::endl;
67       }
68       catch(const py2cpp::Exception& err)
69       {
70         std::cerr << err.what();
71       }
72     }
73     Py_Finalize();
74     return 0;
75   }
76 ________________________________________________________________________________