C and Python call one (import Python module with, get functions and classes)

Source: Internet
Author: User

Python is a very good scripting language, with simple and clear syntax and a rich and powerful class library. It is often nicknamed the Glue language, which makes it easy to make a variety of modules in other languages. But Python interface design we are not very familiar with (although he also has a lot of good and powerful class library, such as Wxpython, etc., but compared to other GUI design, we may be more familiar with Qt or MFC, so we do not use Python as a tool for interface design), So in many cases, it is difficult to use the Python GUI to design a project with interface requirements. But that doesn't mean we can't rely on Python's efficiency and simplicity to do something, we can use Python to do some modules, and then call her in other programming languages, with examples of related functions.

If you call Python in C code, the first thing you need to do is initialize the Python environment. The function used here is py_initialize (). When you have correctly initialized the Python environment, you can use the simplest CPython interface to run some scripts, the function is pyrun_simplestring (s), the function of everyone to see what is used to do it. Using this function allows you to write some python directly in the parameters, and then the Python environment calls this function to complete the Python statement you wrote. For example pyrun_simplestring ("Import Tree"), using this statement, you can use Python in the C environment to load the tree.py module.

Next, we're going to get some of the functions defined in the module, and you know that inside the Python module there are a lot of functions, classes. When we import the relevant modules in Python, we can call them directly, so how do we get these functions and classes in C? What are these functions and classes? This involves some of the basic Python mechanism, in fact, in Python, everything is the object, they have a common base class Pyobject, as for this pyobject concrete is what, here does not unfold. So we can come up with some ideas, since everything is pyobject, then we use Pyobject in C to connect the function with the class is not good.

Now let's go back to our run pyrun_simplestring ("Import Tree"), at which point we have loaded the tree.py module in the running environment, what is this module? According to the above, you should be able to guess, yes, this module is also a Pyobject-based class object. At this point the corresponding function is (Pyobject *) pyimport_importmodule (const char *name) or (Pyobject *) Pyimport_import (Pyobject *name) (the difference between the two is, If you use the latter, you need to convert the module name (usually char*) to a Pyobject object), and you will get a Moudle object of type Pyobject.

For this Moudle object, it is not suspense, it is actually a special Dict object in Python, which contains all kinds of information including all the class functions in this moudle. Therefore, getting the related classes and functions from this moudle is the extremely easy thing. First we return this moudle to a Dict object, using a function of (Pyobject *) pymodule_getdict (Pyobject *) and then using (Pyobject *) pydict_getitemstring ( Pyobject *DP, const char *key) to obtain related functions and classes. If it is a class, then it is just a class definition, and we need to construct it as an object, using the interface (Pyobject *) pyinstance_new (Pyobject *, pyobject *,pyobject *) Specific functions are not expanded here, Let's find it online.

Below is a code on the net, more detailed said this series of processes, we can try, the source URL is not found, tragedy, directly affixed to the code:

def hello (s):

print "Hello World"

Print S

def arg (A, B):

print ' a= ', a

print ' b= ', b

Return a + b

Class Test:

def __init__ (self):

Print "Init"

def say_hello (self, name):

Print "Hello,", name

return name

Pytest.cpp: Defines the entry point of the console application.

//

#include "stdafx.h"

#include <Python.h>

int main (int argc, char* argv[])

{

Initialize Python

Py_initialize ();

Variables that define Python types

Pyobject *pmodule = NULL;

Pyobject *pfunc = NULL;

Pyobject *parg = NULL;

Pyobject *result = NULL;

Pyobject *pclass = NULL;

Pyobject *pinstance = NULL;

Pyobject *pdict = NULL;

Run Python code directly

Pyrun_simplestring ("print ' python start ');

Introducing Modules

Pmodule = Pyimport_importmodule ("Test_code");

Get Module Dictionary Properties

Pdict = Pymodule_getdict (pmodule);

Direct access to functions in the module

PFunc = pyobject_getattrstring (pmodule, "Hello");

Parameter type conversion, passing a string. Convert a C + + type string to a Python type, a python type in a tuple view a Python document

PARG = Py_buildvalue ("(s)", "Hello Charity");

Call the directly obtained function and pass the parameter

Pyeval_callobject (PFunc, PARG);

Get a function from a dictionary property

PFunc = pydict_getitemstring (pdict, "Arg");

Parameter type conversion, passing two integer parameters

PARG = Py_buildvalue ("(I, I)", 1, 2);

Call the function and get the return value of the Python type

result = Pyeval_callobject (PFunc, PARG);

C is used to save the return value of the C + + type

int C;

Convert the return value of a Python type to a C + + type

Pyarg_parse (Result, "I", &c);

Output return value

printf ("a+b=%d\n", c);

To get classes in a module by dictionary properties

PClass = pydict_getitemstring (pdict, "Test");

Instantiate the acquired class

Pinstance = pyinstance_new (pClass, NULL, NULL);

Methods to invoke a class

result = Pyobject_callmethod (pinstance, "Say_hello", "(s)", "Charity");

Output return value

char* Name=null;

Pyarg_parse (result, "s", &name); The second argument of this function is quite lame, depending on the English language below, the type is represented by a character, for example "s"

The str "I" stands for int, and the individual feels rather ridiculous.

printf ("%s\n", name);

Pyrun_simplestring ("print ' Python end ');

Release Python

Py_finalize ();

GetChar ();

return 0;

}

Operation Result:

Python start

Hello World

Hello charity

A= 1

B= 2

A+b=3

Init

Hello, charity.

Charity

Python End

C and Python call one (import Python module with, get functions and classes)

Related Article

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.