Python calls C ++ code

Source: Internet
Author: User

Python calls C ++ code

This document describes how to call C ++ using python using the instance code.
1. if no parameters are passed from python to C ++, the simplest way for python to call C ++ is to declare the function as a C Available function and then be called as a C code by python, as shown on the third floor;
2. swig is the most convenient method to call when parameters are passed to the C ++ function, as shown in the following project;

Rachel. I (swig file ):

%module rachel%{#include rachel.h%}extern int linear(int x, int w, int b);

C ++ code:

Rachel. h:

#include
  
                    #include
   
                    int linear(int x, int w, int b);  
   
  

Rachel. cpp:

#include rachel.h       int linear(int x, int w, int b){     int res = w * x + b;             printf(%d, res);             return res;                  }                                

Run the following command:

swig -c++ -python rachel.ig++ -c -fPIC rachel_wrap.cxx -I/home/zhangruiqing01/.jumbo/include/python2.7 -I./includeg++ -shared rachel.o rachel_wrap.o -o _rachel.so

In the first sentence, swig generates rachel_warp.cxx (if it is C, swig-python rachel. I is used to generate the rachel_warp.c file );
The last sentence generates the dynamic link library _ rachel. so for python calling (if it is C, use ld-shared rachel. o rachel_warp.o-o _ rachel. so );

Python call:

>>> import _rachel>>> _rachel.linear(1,2,5)7

Finally, let's take a look at the program structure in this 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.