Python calls the DLL written in C/C ++

Source: Internet
Author: User

It is equivalent to translating this article. How to Write a DLL/so in C/C ++ for python is intended to comment on my usage failure.

First of all, the author recommends that cython can be used as a better Python encapsulation for C. I didn't use it. Instead, use the vs tool to generate the following DLL.

1. Compile the source code

C program // test. C _ declspec (dllexport) int sum (int A, int B) {return a + B;} c ++ // test. CPP # define dllexport extern "C" _ declspec (dllexport) dllexport int sum (int A, int B) {return a + B ;}

Windows user _ declspec (dllexport) is required and can be accessed without the. Def file. In fact, I don't understand what it means. Linux users can ignore this prefix.

The prefix of C ++ has more extern "C" than that of C. It is used to avoid the compiler from adding additional things. Therefore, if it is a C ++ DLL, it is also necessary. In fact, you can copy the prefix.

In fact, most examples are directly written as extern "C" _ declspec (dllexport) int sum (int A, int B), which is just a matter of readability.

You can also add a header file, similar to the C # interface.

//test.hint sum(int, int);

2. compile it into dll/so

Since we teach you how to generate a DLL directly, instead of creating a class library project, you can directly use the command line tool provided by Vs, navigate to the test. c/test. cpp directory, and then execute:

> Cl/LD test. c

[...]

/Out: Test. dll

/DLL

/Implib: Test. Lib

Test. OBJ

Creating library test. lib and object test. Exp

Note: CL use the file extension (. C or. cpp) to know if the source is written in C or C ++.

Linux users use gcc/g ++ to generate a. So file:

Gcc-wall-wextra-o-ANSI-pedantic-shared test. C-O test. So

Note: The-shared option is responsible to create the. So.

Note: You can also use dependency walker or similar programs to see the list of the exported functions and check if the sum function is there.

Not tested

3. Use the ctypes module to access dll/so

Ctypes has been included by default since python2.5. Otherwise, install (easyinstall or Pip, or download) on your own)

>>> From ctypes import cdll

>>> Mydll = cdll. loadlibrary ('test. dll ')

>>> Mydll

<Cdll 'test. dll ', handle 10000000 at b92310>

Windows automatically searches the current directory. For Linux, enter the path:

>>> From ctypes import cdll

>>> Mydll = cdll. loadlibrary ('/home/wolf/test. so ')

>>> Mydll

<Cdll '/home/wolf/test. so', handle 9ba7d30 at b7e55d2c>

Test:

>>> Mydll. Sum

<_ Funcptr object at 0x00af6918>

>>> Mydll. sum (5, 3)

>>> 8

= Okay. The above is the original text. My problem is as follows:

1. Because the development environment is x64, 64-bit python is installed, and the result is always failed. It is loaded back to the 32-bit version. The above test is passed directly, which is definitely the cause of 64-bit, even if the DLL is compiled on my 64-bit machine. Several Python instances installed with x64 are not successfully tuned.

2. The following is a C method. You need to input an int array and a character array.

int CCaptionApp(int times,int length, int *ids,char *message){    int n,m=0;    for(n=0;n<length;n++)    {        m+=ids[n];    }    return m;}

After the test, the character array can be directly transmitted as a string, and the int array can also be processed as follows:

>>> From ctypes import cdll

>>> Mydll = cdll ('test. dll ') # demonstrate another loading method by the way, with faster writing

>>> Mydll. ccaptionapp (1, 3, [3, 4, 5], 'Hello ')

Output:

Traceback (most recent call last ):

File "<stdin>", line 1, in <module>

Ctypes. argumenterror: argument 3: <type 'exceptions. typeerror'>: Don't know how to convert parameter 3

It seems that this unfortunately cannot be obtained (BTW,. Net can be called directly using int []). I checked the document, section 15.17.1.13 array in it:

>>> From ctypes import *

>>> Tenintegers = c_int * 10

>>> II = tenintegers (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

>>> Print II

<C_long_array_10 object at 0x...>

>>> For I in II: print I,

...

1 2 3 4 5 6 7 8 9 10

>>>

That is, we need to construct an array with length, OK, test:

>>> From ctypes import *

>>> Mydll = cdll ('test. dll ')

>>> Mydll. ccaptionapp (1, 3, (c_int * 3) (3, 4, 5), 'Hello ')

>>> 12

Successful

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.