How Python calls C

Source: Internet
Author: User

Python has been studying the method of Calling C for three days. Today I read a blog
It turns out to be so simple, maybe the simplest method. Below are some ideas

Lab platform:
Windows XP system. The compiling environment is vs2005.

Tutorial steps:
Step 1:
Compile the C Module in vs2005
CodeAs follows:

# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
// # Include "python. H"

_ Declspec (dllexport) int FAC (int n)
{
Printf ("fac FN run. \ n ");
If (n <2)
Return 1;
Return N * FAC (n-1 );
}

Step 2:
Compile and generate DLL Library

Step 3:
Load and test the dynamic library in Python.
The Code is as follows:
Def test_py_call_clib ():
From ctypes import *
Import OS
Test_other = cdll. loadlibrary (OS. getcwd () + '/test_other.dll ')
Print "Load Library success ."
Print test_other.fac (4)

If _ name _ = "_ main __":
Test_py_call_clib ()

Pay attention to loading the dynamic library directory

Reference

Http://coolshell.cn/articles/671.html

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.