Python Embedded C ++ (2)-import module

Source: Internet
Author: User

First, I have to mention a very good website: http://www.codase.com/index.html

This is what I found when searching for Embedded functions. There are a lot of small instance code in it, so it is really time to see (haha)

 

The preceding describes the configurations needed for embedding (see the http://blog.csdn.net/xiadasong007/archive/2009/09/02/4511841.aspx), this time mainly to illustrate how to call the basic methods of functions in the python module in C/C ++.

Prerequisites:

1: pyobject * obj is a bit like a handle in the SDK.

2: Call the python module process: first load the module. After loading, you can directly access it (⊙ o ⊙ ~! Very simple ~

 

Okay. Let's see the code:

# Include "Python/python. H"

# Include <iostream>
Using namespace STD;

 

Int main (INT argc, char ** argv)
{
Pyobject * pmodule, * pfunc, * pvalue;

Py_initialize ();
////////////////

Pmodule = pyimport_importmodule ("mat"); // mat is a small module (mat. py) Written in Python by myself. For details, see the appendix below.

Pvalue = pyobject_callmethod (pmodule, "add", "II",); // directly access the function add (A, B) in the module through the module obtained above)

// Note that the "II" here is actually equivalent to the "% d" feature in C. Please refer to the documentation
Cout <pylong_aslong (pvalue) <Endl; // convert the obtained pvalue value to the long type in C.

 

Pfunc = pyobject_getattrstring (pmodule, "add"); // you can use this function to obtain the function object.
Pvalue = pyobject_callfunction (pfunc, "II",); // execute a function through a function object
Cout <pylong_aslong (pvalue) <Endl;
////////////////
Py_finalize ();
Return 0;
}

 

// Appendix: mat. py

/*

Def add (A, B ):

Return A + B

*/

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.