"Python Coolbook" CType read Linux dynamic library so file

Source: Internet
Author: User
Tags gcd greatest common divisor

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.