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.