_php tutorial on calling relationships between C/python

Source: Internet
Author: User
Tags python list

Call relationships between C/python


Because Python has a lot of powerful open source libraries, C can borrow methods to do more.

So C's method of calling Python is especially important.

Method/Step

  1. Ubuntu 14.04 Linux C

    GCC (Ubuntu 4.8.2-19ubuntu1) 4.8.2

    Python 2.7.6

  2. File 1 [python file]: math_test.py


    Def Add_func (A, B):

    Return a+b


    Def Sub_func (A, B):

    Return (A-B)


    File 2 [C source file]: c_call_python.c


    #include

    #include

    #include

    #include "Python2.7/python.h"


    int main (int argc, char** argv)

    {

    int arg0 = 0,ARG1 = 0;

    if (argc = = 3) {

    arg0 = Atoi (argv[1]);

    Arg1 = Atoi (argv[2]);

    }else{

    printf ("Please input 2 args!! \ n ");

    return-1;

    }


    Py_initialize ();

    if (! Py_isinitialized ())

    return-1;

    pyrun_simplestring ("Import sys");

    Pyrun_simplestring ("Sys.path.append ('./')");

    Pyobject *pmodule;

    Pyobject *pfunction;

    Pyobject *pargs;

    Pyobject *pretvalue;


    Pmodule = Pyimport_importmodule ("Math_test");

    if (!pmodule) {

    printf ("Import python failed!! \ n ");

    return-1;

    }


    Pfunction = pyobject_getattrstring (Pmodule, "Add_func");

    if (!pfunction) {

    printf ("Get Python function failed!!! \ n ");

    return-1;

    }



    PArgs = Pytuple_new (2);

    Pytuple_setitem (PArgs, 0, Py_buildvalue ("I", arg0));

    Pytuple_setitem (PArgs, 1, Py_buildvalue ("I", arg1));


    Pretvalue = Pyobject_callobject (pfunction, PArgs);

    printf ("%d +%d =%ld\n", Arg0,arg1,pyint_aslong (Pretvalue));


    Py_decref (Pmodule);

    Py_decref (pfunction);

    Py_decref (PArgs);

    Py_decref (Pretvalue);


    Py_finalize ();

    return 0;

    }

  3. 3

    root@linux:~/code# Gcc-o C_call_python c_call_python.c-lpython2.7

    root@linux:~/code#./c_call_python 12 15

    12 + 15 = 27

    The Py_buildvalue () function in the Python extension

    The Py_buildvalue () function, in contrast to Pyarg_parsetuple (), is the transformation of the C-type data structure into a Python object, the prototype of the function: Pyobject *py_buildvalue (Char *format, ...) The function can recognize a series of format strings like the Pyarg_parsetuple () function, but the input parameter can only be a value, not a pointer. It returns a Python object. Unlike Pyarg_parsetuple (), the Pyarg_parsetuple () function has its first parameter as a tuple, and py_buildvalue () does not necessarily generate a tuple. It generates a tuple only if the format string contains two or more format units, and if the format string is empty, returns none. In the following description, the item in parentheses is the type of Python object returned by the format unit, and the entry in square brackets is the value of the passed C. "S" (string) [char *]: Converts the C string to a Python object and returns none if the C string is null. "s#" (string) [char *, int]: Converts the C string and its length to a Python object, if the C string is a null pointer, the length is ignored, and none is returned. "Z" (String ornone) [char *]: function with "s"."z#" (String ornone) [char *, int]: function with "s#"."I" (integer) [int]: Converts an int of type C to a Python int object. "B" (integer) [char]: function with "I". "H" (integer) [short int]:function with "I". "L" (integer) [long int]: Converts a long of type C to an int object in Pyhon. "C" (string of length 1) [char]: Converts a char of type C to a Python string object of length 1. "D" (float) [double]: Converts a double of type C to a floating-point object in Python. "F" (float) [float]:function with "D". "o&" (object) [converter,anything]: Converts any data type to a Python object through a conversion function, which is called as a parameter of the conversion function and returns a new Python object if an error occurs that returns NULL. [Items] (tuple) [Matching-items]: Converts a series of c values to a Python tuple. [Items] (list) [Matching-items]: Converts a series of c values into a python list. "{items}" (dictionary) [Matching-items]: Converts the C value of a series of classes into a Python dictionary, Each pair of consecutive C values is converted into a key-value pair.
    example: Py_buildvalue ("") None Py_ Buildvalue ("I", 123) 123 Py_buildvalue ("III", 123, 456, 789) (123, 456, 789) py_buildvalue ("s", "Hello") ' Hello ' PY_BUILDV Alue ("ss", "Hello", "World") (' Hello ', ' world ') Py_buildvalue ("s#", " Hello ", 4) ' Hell ' Py_buildvalue (" () ") () Py_buildvalue ("(i)", 123) (123,) Py_buildvalue ("(ii)", 123, 456) (123, 456) Py_buildvalue ("(i,i)", 123, 456) (123, 456) Py_buildvalue ("[I,i]", 123, 456) [123, 456] Py_buildvalue ("{s:i,s:i}", "ABC", 123, "Def", 456) {' abc ': 123, ' Def ': 456} py_ Buildvalue ("(((ii) (ii)) (ii)", 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))

    Deep analysis of C + + calling Python module





    Python provides a C + + library that makes it easy for developers to invoke Python modules from C + + programs. Next through this article to introduce the C + + call Python module knowledge, need to refer to the friend

    Generally developed games know that Lua and C + + can be a good combination of each other, the Lua script as a similar dynamic link library to use, good use of the flexibility of script development. And as a popular general-purpose scripting language, Python is also possible. In a C + + application, we can use a set of plug-ins to implement some of the functions of the unified interface, the general plug-ins are implemented using the dynamic link library, if the plug-in changes more frequently, we can use Python instead of the dynamic link library form of plug-ins (as a text-style dynamic link library), This makes it easy to rewrite the script code as the requirements change, rather than having to recompile the link binary's dynamic-link library. The flexibility has been greatly improved.

    As a glue language, Python can easily invoke C, C + + and other languages, and can also invoke Python's modules in other languages.

    Python provides a C + + library that makes it easy for developers to invoke Python modules from C + + programs.

    Specific documentation Reference Official guide:

    Embedding Python in another application

    Calling methods

    1 link to Python call library

    The Python installation directory already contains header files (include directories) and library files (Python27.lib under Windows).

    You need to link to this library before you use it.

    2 Calling Python statements directly

    #include "python/Python.h"int main(){Py_Initialize(); ## 初始化PyRun_SimpleString("print 'hello'");Py_Finalize(); ## 释放资源}

    3 Loading the Python module and calling the function

    The ~/test directory contains test.py:

    def test_add(a, b):print 'add ', a, ' and ', breturn a+b

    You can call the Test_add function with the following code:

    #include "Python/python.h" #include
              
               
    Using namespace Std;int Main () {py_initialize ();//Initialize//To switch the Python work path to the directory where the module is to be called, make sure that the path name is correct string path = "~/test"; String chdir_cmd = String ("Sys.path.append (\") + path + "\") "; const char* cstr_cmd = Chdir_cmd.c_str (); pyrun_simplestring ("Import sys"); Pyrun_simplestring (cstr_cmd);//load module pyobject* modulename = pystring_fromstring ("test"); Module name, not file name pyobject* Pmodule = Pyimport_import (ModuleName), if (!pmodule)//Load module failed {cout << [ERROR] Python get Modu Le failed. "<< Endl;return 0;} cout << "[INFO] Python get module succeed." << endl;//load function pyobject* PV = pyobject_getattrstring (Pmodule, "tes T_add "); if (!PV | |! Pycallable_check (PV))//Verify Load Success {cout << "[ERROR] Can ' t ' find Funftion (test_add)" << Endl;return 0;} cout << "[INFO] Get function (Test_add) succeed." << endl;//Set parameters pyobject* args = pytuple_new (2); 2 parameters pyobject* arg1 = Pyint_fromlong (4); Parameter one is set to 4pyobject* arg2 = Pyint_fromlong (3); Parameter two is set to 3pytuple_setitem (args, 0, arg1); Pytuple_SetItem (args, 1, arg2);//Call function pyobject* PRet = Pyobject_callobject (PV, args);//Gets the parameter if (PRET)//verifies whether the call succeeded {long result = Py Int_aslong (PRet); cout << "Result:" << result;} Py_finalize (); # # Release resource return 0;}
              

    Parameter passing

    1 C + + passes parameters to Python

    The parameters of Python are actually tuples, so the arguments actually construct an appropriate tuple.

    There are two ways to use it:

    Creating tuples with Pytuple_new, pytuple_setitem setting tuple values

    PyObject* args = PyTuple_New(3);PyObject* arg1 = Py_BuildValue("i", 100); // 整数参数PyObject* arg2 = Py_BuildValue("f", 3.14); // 浮点数参数PyObject* arg3 = Py_BuildValue("s", "hello"); // 字符串参数PyTuple_SetItem(args, 0, arg1);PyTuple_SetItem(args, 1, arg2);PyTuple_SetItem(args, 2, arg3);

    Using Py_buildvalue to construct tuples directly

    PyObject* args = Py_BuildValue("ifs", 100, 3.14, "hello");PyObject* args = Py_BuildValue("()"); // 无参函数

    Format strings such as I, S, and F can refer to format strings

    2 Convert Python return value

    All the calls to Python get are pyobject objects, so you need to use some of the functions in the library provided by Python to convert the return value to C + +, such as pyint_aslong,pyfloat_asdouble, pystring_asstring, and so on.

    You can also use the Pyarg_parsetuple function to parse the return value as a tuple.

    Pyarg_parse is also an easy-to-use conversion function.

    Pyarg_parsetuple and Pyarg_parse both use format strings

    Precautions

    The need to switch Python's working directory to the module's path is loaded by module name instead of file name module load or the function load needs to be validated for success, otherwise it may cause a stack error to cause the program to crash by using Py_decref (pyobject*) to dismiss the object's reference ( For Python garbage Collection)

http://www.bkjia.com/phpjc/1121870.html www.bkjia.com true http://www.bkjia.com/phpjc/1121870.html techarticle c/python Because Python has a lot of powerful open source libraries, C can borrow methods to do more. So C's method of calling Python is especially important. Method ...

  • < b style= "Font-size:large;line-height:normal;" >
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.