Call C's dynamic link library with Python

Source: Internet
Author: User

Temporarily python is not well written, some things still write with C handy, encounter this situation how to do it ... So I learned a bit about Python's method of invoking the C Dynamic link library. In this way, a function written in C can be provided to Python for use.

First, you will first create a new DLL project. For example, I created a new dlllearning project with two files in Example.h and Example.cpp.

The code is as follows:

1 //example.h2 #ifndef Export_example_dll3 #defineExample_api __declspec (dllimport)4 #else5 #defineExample_api __declspec (dllexport)6 #endif7 8 9 extern "C" {TenExample_apiintMaxint,int); OneExample_apiintMinint,int); A}
1 //Example.cpp2 #defineExport_example_dll3#include"example.h"4 5Example_apiintMaxintAintb) {6     returna > B?a:b;7 }8 9Example_apiintMinintAintb) {Ten     returnA < b?a:b; One}

Refer to this blog post about the role of __declspec (dllimport): http://blog.csdn.net/mniwc/article/details/7993361

Note that extern "C" is a must, if compiled according to C + +, there will be unexpected problems occur, prompt the following:

Traceback (most recent):    mx = Dlllearning.max (A, b)  File ' E:\Python34\lib\ctypes\__init__.py ', line 364, in __getattr__    func = self.__getitem__ (name)  File ' E:\Python34\lib\ctypes\__init__.py ', line 369, in __ getitem__    func = self._funcptr ((name_or_ordinal, self)) attributeerror:function ' Max ' isn't found[finished in 0.2s]

Compile the build DLL file, and we'll call it with Python.

1  from Import *2 dlllearning = Cdll. LoadLibrary ('dlllearning.dll')3 a = 4134 b =5 /mx = Dlllearning.max (A, b) 6 mn = Dlllearning.min (A, b)7print(MX, MN)

Output Result:

413 52[finished in 0.2s]

Suddenly feel the door of a new World open

Call C's dynamic link library with Python

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.