Python calls C++ DLL parameter transfer skills

Structure parameters: http://www.jb51.net/article/52513.htm

 

 

Ready to work:

C++ file (cpp): (note the addition of extern "C" to the function declaration)

#include <stdio.h>
 
extern "C" {
    __declspec(dllexport) int Double(int x);
    __declspec(dllexport) float floatAdd(float a,float b); 
    __declspec(dllexport) void HelloWorld(char * str); 
    __declspec(dllexport) void Ints(int * arr,int n); 
}
 
int Double(int x){
    return x*2;
}

float floatAdd(float a,float b) {
    return a+b;
}

void HelloWorld(char * str){
    puts(str);
}

void Ints(int * arr,int n){
    for(int i=0;i<n;i++){
        printf("%d ",arr[i]);
    }
    puts("");
}

Compiled to dll with g++ (mingw 64 bit):

g++ dlltest.cpp -shared -o dlltest.dll -Wl,--out-implib,dlltest.lib
pause

Load dll in python script:

from ctypes import *
dll = cdll.LoadLibrary('DLL/dlltest.dll')

 

1. If no modification is added , the default incoming parameter is int, and the outgoing parameter is also int

 

2. For types other than int (such as float), you need to declare the incoming parameter type and outgoing parameter type of the python function

fun.argtypes=[c_float,c_float] #Define   the parameter type fun.restype 
=c_float #Define              the return value type 
a=fun(c_float(1.4),c_float(1.2 ))
 print (type(a))
 print (a)

output:

<class 'float'>
2.5999999046325684

 

3. For the string char* , when declaring the incoming parameter type, you need to declare it as a character pointer , then allocate a char array , and finally cast the array to a character pointer

Moreover, when importing the data structure in the python script into c++, it is necessary to convert str to bytes or bytesarray type , and perform iterator decomposition

hello=dll.HelloWorld
hello.argtypes =[POINTER(c_char)] #The     incoming parameter is a character pointer 
STR=(c_char * 100)(*bytes( "I believe you are still here " , ' utf-8 ' )) # Put a group of 100 Character is defined as STR 
cast(STR, POINTER(c_char))
hello(STR)

output:

I believe you are still here

 

4. For arrays of other data types , (such as int*), the operation is similar:

Ints=dll.Ints
Ints.argtypes=[POINTER(c_int),c_int]
INT =(c_int * 100)(*[1,2,3]) #Pass the list into variable-length parameter args* 
cast(INT, POINTER(c_int))
Ints(INT,c_int(3))

output:

1 2 3

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325890502&siteId=291194637