Home Backend Development Python Tutorial Detailed explanation of how Python calls C/C++ underlying libraries and transfers values ​​to each other

Detailed explanation of how Python calls C/C++ underlying libraries and transfers values ​​to each other

Feb 20, 2017 am 10:32 AM

As a script interpretation language, Python itself is well integrated with C++, so using Python to develop and call the C/C++ underlying library where performance requirements are required is simply an artifact. This article introduces in detail the problem of Python calling C/C++ underlying libraries and passing values ​​to each other. Let’s take a look.

Preface

Development environment:

Centos 7 + Python 3.5.1 + Qt Creator (just compiled with Qt Creator, and does not use any libraries of QT)

Python calls C/C++ libraries, there are two ways I can do it now

1.extern "C" export (It is troublesome to pass values ​​to each other, this method is not recommended):

Make the C/C++ library the same DLL or .so as usual, for example:

//.h文件
#include <Python.h>
//.cpp文件
//C/C++ my.so 或者my.dll
enter "C" void printHello()
{
  std::cout<<"Hello World"<<std::endl;
}
Copy after login

#Python
import ctypes 
from ctypes import *
loadso = ctypes.cdll.LoadLibrary 
mylib = loadso("./my.so")
mylib.printHello()
>>>Hello world
Copy after login

Code explanation:

my.so There is a C export functionprintHello()

import ctypes : Import an official library, as the name suggests, it is related to C

loadso = ctypes.cdll.LoadLibrary : loadso represents the function used to load the library

mylib = loadso(“./my.so”)  //Or loadso(“my.dll”) Load my.so library

mylib.printHello(): Call Library function

The above code can output normally: Hello World, but they do not pass values ​​to each other

Python and C++ pass values ​​to each other

//.h文件
#include <Python.h>
//.cpp文件
enter "C" int printHello(const char* str)
{
  std::cout<<str<<std::endl;
  return 1;  
}
Copy after login

Then the problem with Python comes

str = create_string_buffer(b"Hello World")
#mylib.printHello("Hello World") 这里死活就是显示:H,*(str+4)才是&#39;e&#39;,*(str+8) 是&#39;l&#39; 依次类推
print (mylib.printHello(str))
>>>Hello World
>>>1
#由于对Python不是特别的熟悉 怎么也做不到显示C++返回的字符串, Python只能显示C++返回的字符串子能看到一个地址而已
Copy after login

2.Python extension C/C++

Not much to say, just go to the code

//.h文件 本来这是C++连接Mysql 我只摘抄部分代#include <Python.h>
//.cpp文件
//传递多个参数 Python传过来的参数在args里面
PyObject* printfHello(PyObject* self,PyObject* args)
{
  int i=0
   const char* str;
  if (!PyArg_ParseTuple(args, "i|s", &i,&str))   //i 表示整形 s 表示字符串
    return PyLong_FromLong(0);
  print("%d,%s",i,str);
  return Py_BuildValue("s","OK");  //向Python返回OK字符串
}
//映射 知道MFC的一看就懂
static PyMethodDef MyMethods[] = {
{"printfHello", printfHello, METH_VARARGS,  //"printHello" 中可调用的函数 METH_VARARGS :带有参数   METH_NOARGS:无参数
"print"},   //说明
{"connect", connect, METH_VARARGS,
"connect mysql"},
{NULL, NULL, 0, NULL}
};
static PyObject* UtilError;
// 向Python中注册模块
static struct PyModuleDef spammodule = { 
PyModuleDef_HEAD_INIT,
"libMysqlUtil", //模块名字 import libMysqlUtil
"C++ Connect Mysql",
-1,
MyMethods
};//PyInit_libMysqlUtil 注意名字 一定要PyInit_ 加上你的模块名字 不然Python import 会提示没有定义 PyInit_你的模块名字 PyMODINIT_FUNC PyInit_libMysqlUtil(void) { PyObject* m = nullptr; m = PyModule_Create(&spammodule);
//m= Py_InitModule(....) Python 2.7 if(!m) { return m; } UtilError = PyErr_NewException("Util.error",NULL,NULL); Py_INCREF(UtilError); PyModule_AddObject(m,"error",UtilError); return m; }
Copy after login

#python
import libMysqlUtil
libMysqlUtil.printHello(1,"hello World")
>>>1,hello World
>>>OK
Copy after login

Summary

So far, Python and C/C++ communicate with each other and can meet most needs. Structure value transfer has not been studied yet. For classes, just use pointers. , there is a pointer in C++, and the pointer is converted into an integer in Python. When Python passes this integer to C++, it uses PyArg_ParseTuple to turn the integer into a class pointer.

For more detailed explanations of how Python calls C/C++ underlying libraries and transfers values ​​to each other, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles