search
HomeBackend DevelopmentPython TutorialDetailed introduction to calling each other between python and C

Detailed introduction to calling each other between python and C

Jul 16, 2017 pm 12:03 PM
pythonmethodDetailed explanation

Although Python has high development efficiency, as a scripting language, its performance is not high. Therefore, in order to balance development efficiency and performance, modules with high performance requirements are usually implemented in C or C++ or run Python scripts in C or C++. To handle logic, the former is usually the implementation of some modules in python, and the latter is more common in server-side programs (implementing business expansion or plug-in functions) and game development (scripts only handle logic). This article mainly introduces how to realize mutual calls between python and c by running python scripts in c, and uses the example of setting the same memory area in c and python scripts.

Preface

Recently due to work needs, I am considering making a data synchronization protocol based on udp for online game battles, for preliminary testing For data, we decided to make an external proxy tunnel first. The principle is to establish network forwarding proxies on the server side and client side respectively, that is, the original C/S connection is changed to rapid data transmission between the two proxies. Because the udp library is code written in C++, it is very annoying to constantly modify parameters, recompile, modify output statistical data and tabulate when testing data. Finally, it was decided to use a python script to make logical calls to the export interface. Not much to say below, let’s take a look at the detailed introduction:

Preparation work

In order to run a python script in c, you need to add python when linking the program. The virtual machine library is linked in. The python virtual machine library is the python27.lib file in the libs in the python installation directory. As for how to link the library into the program, you can google it yourself. Since some methods and data structures of Python are used in C, the include directory under the Python installation directory needs to be added to the project include directory. Okay, that's all you need to prepare, and then you can start to implement an example of setting a memory area.

There are many ways to export C/C++ to python. According to different needs, you can use the following different methods:

1. ctypes binding. ctypes is included in the universal python standard library module. It can load dynamic link libraries (dll, so) at runtime and is supported on CPython 2.x/3.x and PyPy. The advantage of this method is that you don’t need to write the export function specifically using the python api. You can directly load the symbol table of the dynamic link library and call it directly in python.

2. Third-party python binding. Examples include boost-python, which is implemented by tool automation using Python/C api to generate a series of C++ wrapper functions. Especially suitable for exporting large libraries or engines to python.

3. Manually write the python binding function. If you are familiar with the Python C API, this method should be the most flexible and you can use it after reading the API documentation. In theory, the efficiency should be the best, but for a python beginner like me, it may take a lot of time.

Based on my previous experience of exporting C functions to Lua scripts, I thought I would have to study the python c api first and then work on it for a long time before I could get it done. Later I found that the ctypes of the Python standard library module is already very powerful. Although the performance should be the worst among the three methods, in this tunnel with a maximum of 60fps, the loss of C/Python interface boundary calls is ignored for the first time. Different from the other two design methods, ctypes uses a non-invasive method of calling the interface. There is no need to modify the original C interface or write some binding code, and directly call the compiled dynamic library. The process of using ctypes is also very pleasant.

The following introduces the use of ctypes:

1. Load DLL dynamic link library

Here you need to pay attention to distinguish whether the dynamic link library function uses the cdecl or stdcall calling convention, and uses cdll or windll to load the dynamic library respectively.

For example:

# 加载udp库函数 
udp_server = cdll.LoadLibrary("./udp_server.so") 
init_udp_server = udp_server.init_udp_server 
destroy_udp_server = udp_server.destroy_udp_server 
update_udp_server = udp_server.update_udp_server 
SendMsg = udp_server.SendMsg 

SetConnectCallback = udp_server.SetConnectCallback 
SetDisconnectCallback = udp_server.SetDisconnectCallback 
SetTimeoutCallback = udp_server.SetTimeoutCallback 
SetRecvCallback = udp_server.SetRecvCallback

2, Data typeMapping

In addition to the basic data defined by ctypes Types (c_char, c_int, c_double, etc.) can also be converted to pointer types using the pointer function. For the network library to be exported, it is essential to set the callback function. In the C++ library, the callback function is completed by setting a function pointer. ctypes also supports function pointers. statement. For example: recv_cb = CFUNCTYPE(None, c_char_p, c_int), indicating a callback function with a return value of void and parameters of char* and int types.


def init(self, port, ip="127.0.0.1"): 
  self._port = port 
  self._ip = ip 

  self._clients = {} 

  self.c_connect_cb = connect_cb(self.server_connect) 
  self.c_disconnect_cb = disconnect_cb(self.server_disconnect) 
  self.c_timeout_cb = timeout_cb(self.server_timeout) 
  self.c_recv_cb = recv_cb(self.server_recv) 

def create(self): 
  if self._port: 
   if init_udp_server(self._ip, self._port) == 0: 
    print "server listen %s:%d" % (self._ip, self._port) 
    SetConnectCallback( self.c_connect_cb ) 
    SetDisconnectCallback( self.c_disconnect_cb ) 
    SetTimeoutCallback( self.c_timeout_cb ) 
    SetRecvCallback( self.c_recv_cb ) 
    return True 
  print "[error] init_udp_server error", self._ip, self._port 
  return False

It should be noted when binding callback parameters that the bound callback function needs to be saved as a member variable (the above writing method) in order to avoid python garbage collection causing the callback function Become a wild pointer. This is considered a small pit. Basically, a small library only uses these functions.

The above is the detailed content of Detailed introduction to calling each other between python and C. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

See all articles

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 Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),