Python calls C + +

Source: Internet
Author: User

/***gcc-o libpycall.so-shared-fpic pycall.c*/  #include <stdio.h>  #include <stdlib.h>  int Foo (int a, int b)  {    printf ("You input%d and%d\n", A, b);    return a+b;  }  

Python calls the file for the dynamic library: pycall.py

Import ctypes  ll = ctypes.cdll.LoadLibrary   lib = ll ("./libpycall.so")    Lib.foo (1, 3)  print ' * * * finish*** '  

Python calls C + + (Class) dynamic-link library

extern "C" is required to assist, that is, you can only call the C function, you cannot call the method directly, but you can parse the C + + method. Instead of using extern "C", the built-in dynamic-link library does not have a symbol table for these functions.

#include <iostream>using namespace Std;class testlib{public    :        void Display ();        void display (int a);}; void TestLib::d isplay () {    cout<< "first display" <<ENDL;} void TestLib::d isplay (int a) {    cout<< "Second display:" <<A<<ENDL;} extern "C" {    TestLib obj;    void display () {        obj.display ();       }    void Display_int () {        obj.display (2);       }}

g++ compilation generates a dynamic library libpycall.so:g++-O libpycallclass.so-shared-fpic pycallclass.cpp.
Python calls the file for the dynamic library: pycallclass.py

Import Ctypesso = Ctypes.cdll.LoadLibrary lib = so ("./libpycallclass.so") print ' Display () ' Lib.display () print ' Display ( (+) ' Lib.display_int (100)

Reprint: http://blog.csdn.net/taiyang1987912/article/details/44779719

Python calls C + +

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.