C/c++ and python mixed programming experiment 1

1. Call python in c/c++

1️⃣Call python built-in functions in c/c++

Because when we write c/c++ to reference python, we often need python's c interface, which is the header files and third-party library files under the include and libs directories of our python installation directory, that is, .h files and .dll files. The simplest way is to put the include directory and libs directory in the project directory, that is, the directory where the .vcxproj file is located. The easiest
Insert image description here
way is to right-click to open your project menu, and then click Open [Open Folder in File Explorer]. Then add the Python.h header file to the code

#include <D:\Python39\include\Python.h>
#include <iostream>

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

	Py_Initialize();//初始化python解释器
	PyRun_SimpleString("print('Hello, world')\n");//调用python内置函数print
	Py_Finalize();//销毁python解释器
	system("pause");
	return 0;
}

I only added my libs directory above, so the absolute path is used to add the header file. If you add the include directory to the project, then use the relative path include/Python.h. Then
our additional dependencies are
Insert image description here
in the additional library directory. Just add the libs directory, and we can use python's c interface for programming.
The running results are as follows:
Insert image description here
Environment to note:
The environment of your vs project must be the same as the environment of the python interpreter. For example, mine is 64-bit, and my vs environment is set to the x64 environment.
Insert image description here

The official description of Python’s C interface can be found here

2️⃣c/c++ calls python script

First, we create a python script
Insert image description here

Regarding calling the script, add the use of PyObject on the basis of the above, and add the corresponding module for corresponding use. The specific process can refer to the normal python code flow: import module, call specific functions or corresponding.
Note: If you are using a newer version of python, there will be some problems with your calls. Regarding PyEval_CallObject, because it is actually a macro definition and an encapsulation of PyEval_CallObjectWithKeywords, so when you run it, you will see that PyEval_CallObjectWithKeywords has been deprecated. Information. Use a variant of PyEval_CallObject.
code show as below:

#include <D:\Python39\include\Python.h>
#include <iostream>

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

	Py_Initialize();
	PyObject *pModule, *pFunc = nullptr;
	if (Py_IsInitialized()) {
    
    
		PyRun_SimpleString("import sys");
		PyRun_SimpleString("sys.path.append('./')");
		pModule = PyImport_ImportModule("test");

		if (!pModule) {
    
    
			std::cout << "导入模块失败" << std::endl;
		}
		else {
    
    
			pFunc = PyObject_GetAttrString(pModule, "sayhi");
			if (!pFunc) {
    
    
				std::cout << "导入函数失败" << std::endl;
			}
			else {
    
    
				PyObject_CallObject(pModule, nullptr);
			}
		}
	}
	else {
    
    
		std::cout << "初始化失败" << std::endl;
	}

	Py_Finalize();
	system("pause");
	return 0;
}

The output result failed as expected. . . . . .
Insert image description here
After checking a lot of information, I found out that it seems to be due to a problem with my py file name. Because python itself has a test module, when I named it test, I called python’s built-in test, so the function could not be found. However, this can also be called directly when you use python to make direct calls instead of python's c interface. The result is as follows:

PS H:\project\c&c++ course\call_python\call_python> python
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May  3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> test.hi
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'test' has no attribute 'hi'
>>> test.sayhi()
Hello, world.
>>>

OK, I changed it and it failed to run. . . . . .
Insert image description here
Now the internal functions cannot be called, but there are too many interfaces and too little information, so I will put it on hold for now.

Next next section

Guess you like

Origin blog.csdn.net/weixin_44948269/article/details/121598376