One, the dynamic library file generation source file hello.c
#include "hello.h" #include <stdio.h>void hello (const char *name) { printf ("Hello%s!\n", name);} int factorial (int n) { if (n < 2) return 1; return factorial (n-1) * N;} /* Compute The greatest common divisor */int gcd (int x, int y) { int g = y; while (x > 0) { g = x; x = y% x; y = g; } return g;}
Header file Hello.h
#ifndef _hello_h_#define _hello_h_#ifdef __cplusplusextern "C" {#endifvoid HELLO (const char *); int factorial (int n); int g CD (int x, int y); #ifdef __cplusplus} #endif #endif
If the structure is placed in an. h file and is written in. c, there is no difference, and the duplicate definition will be error-free.
If the C + + attribute is used (the. c file needs to be a. cpp file), the. h header requires a corresponding declaration, and the following structure is more insured,
#ifndef __sample_h__#define __sample_h__#ifdef __cplusplusextern "C" {#endif/* Declaration body */#ifdef __cplusplus} #endif #endif
compiling so dynamic libraries
Gcc-shared-fpic-o libhello.so hello.c
You can now see the so file under the folder.
Second, use Python to call the C function
Try to use the cTYPES module to load the library and call the function,
From ctypes import cdlllibhello= Cdll. LoadLibrary ("./libhello.so") Libhello.hello (' you ') Res1 = libhello.factorial (+) Res2 = LIBHELLO.GCD (2) print ( LIBHELLO.AVG) print (res1, res2)
>>> python hello.py
Hello Y!
<_funcptr Object at 0x7f9aedc3d430>
0 2
function Hello is inconsistent with what we expected, just output the first letter "Y", for cookbook other C functions actually I did import, but the data format C and Python is needed to convert, call is not very easy to do, this article focuses on the successful import of Python, After the question is said.
"Python Coolbook" CType read Linux dynamic library so file