Python calls C and C ++ code (boost)

Source: Internet
Author: User

This article describes how to use functions or classes written in C ++ and allows python to call python. First, let's look at the C ++ functions and classes we designed.

# Include <string>
# Include <windows. h>

// Define a function
Void msgbox (const STD: string & Str)
{
MessageBox (0, str. c_str (), "msgbox", mb_ OK );
}

// Define a C ++ class
Class hello
{
Public:

STD: String m_str;

Public:

Hello ()
{
MessageBox (0, "called HELLO: Hello ()", "hello", mb_ OK );
}

Void setmsg (const STD: string & Str)
{
M_str = STR;
}

Void showmsg ()
{
MessageBox (0, m_str.c_str (), "hello", mb_ OK );
}
};

To export the class and function modules that can be used by python, we use the python module in boost.

# Include <boost/python. HPP>

Boost_python_module (pytest) // This pytest is the name of the referenced module in Python, which is imported using import. And the DLL name must be the same. The extension can be retained by the DLL itself.
{
Using namespace boost: Python;

// Export the C ++ class, pay attention to the format, and there is the init behind it. If the constructor has parameters, you need to add them here
Class _ <Hello> ("hello", init <> ())
. Def ("setmsg", & Hello: setmsg) // map the member function
. Def ("showmsg", & Hello: showmsg) // MAP member functions
;

// Export a C function for calling
Def ("msgbox", msgbox); // ing Function
}

Here, you also need to create a DLL project, add the two source codes to the project, and compile them into a DLL.

The following is called in Python:
From pytest import *

Megbox ('Call the C function, I am the function in the dll ')

H = Hello ()
H. setmsg ('I am called in the script ')
H. showmsg ()

Use idle to load and press F5 to execute the script.

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.