This is the 22nd day of my participation in the August Wen Challenge.More challenges in August
Hardware and software Environment
- Ubuntu 18.04 64 – bit
- windows 10 64bit
- Python 3.5.1 track of
- GCC 4.9
- visual studio
preface
In Python development, you sometimes run into a problem that needs to be solved by calling one of C’s dynamically linked libraries. This article takes a look at how Python calls on Windows and Linux systems.
Dynamic library for Linux
Write a simple C code, test.c
#include <stdio.h>
#include <stdlib.h>
char * printStr(const char *p,const char *q)
{
printf("%s",p);
printf("%s",q);
return "xgx";
}
Copy the code
Run the following command to compile the dynamic link library
gcc -fPIC -shared -o libtest.so test.c
Copy the code
To call functions from the C library (as well as C++), use the module ctypes, see the example
from ctypes import *
handle = cdll.LoadLibrary('libtest.so')
func = handle.printStr
func.argtypes = (c_char_p,c_char_p)
func.restype = c_char_p
tmp = handle.printStr("hello".encode("utf-8"),"world".encode("utf-8"))
print(tmp.decode("utf-8"))
Copy the code
Program execution result
helloworldxgx
Copy the code
Application to explain
func.argtypes = (c_char_p,c_char_p)
func.restype = c_char_p
Copy the code
Encode (utF-8) : encode(utF-8) : encode(utF-8) : encode(utF-8) : encode(utF-8) : encode(utF-8) : encode(utF-8)
handle = cdll.LoadLibrary('libtest.so')
ret = handle.printStr("hello".encode("utf-8"),"world".encode("utf-8"))
Copy the code
For the setting of argtypes for other data types, see The links in Resources
Dynamic library for Windows
Visual Studio compiles the DLL and adds a __declSpec (DLlexPort) in front of the methods that need to be thrown, such as the C code below
__declspec(dllexport) unsigned int crc32( const unsigned char *s, unsigned int len)
{
unsigned int i;
unsigned int crc32val=0xffffffff;
printf("len==%d\n",len);
for (i = 0; i < len; i ++)
crc32val = crc32_tab[(crc32val ^ s[i]) & 0xff] ^ ((crc32val >> 8)&0x00FFFFFF);
return ~crc32val;
}
Copy the code
Then open the VS X64 tool command line prompt, enter the C source directory, execute the following two commands respectively, the first command is to generate object file. Obj, the second command is to link object file, generate dynamic library.
cl /c crc.c
link /dll crc.obj
Copy the code
At this point, the DLL file is generated, it is the dynamic link library we need, DLL call with so method.
The resources
- Docs.python.org/3/library/c…